On Tuesday 19 June 2007 07:00:24 Titi Anggono wrote:
> Hi all,
>
> I want to create an array consisting strings, but I
> don't know where I made those mistakes.
>
> Here is part of code
> ==================
> .....
> char *arrayA[5]; /*name of array variable that
> stores strings*/
> char stations[10];
>
> i=0;
> while(fscanf(fileopen,"%s",&stations) != EOF){
> arrayA[i] = stations;
> printf("%s\n",arrrayA[i]); //Print1
> i++;
> }
>
> fclose(ffileopen);
>
> for(i = 0;i < 5;i++){
> printf("%s\n",arrayA[i]); //Print2
> }
> ==============================
>
> Print1 gives result what I want since it equals to
> scan the data. But Print2 gives me wrong result, the
> output is the last input of variable stations. For
> example,
> the output Print1 is
> LAT1
> LAT2
> LAT3
> LAT4
> LAT5
> but, the output of Print2 is
> LAT5
> LAT5
> ..
> ..
> LAT5
>
> Thanks for any explanations.
>
> Titi
Hi,
Just at the glance it seems that you missused the pointers.
With the following
char *arrayA[5];
you made array of five pointers, and with this
arrayA[i] = stations;
you are only setting those pointers to point to address of "stations". So in
the first loop, while "stations" variable is changing it prints "correct"
values, but in the second loop "stations" remains the same (retains the last
value) thus and all those pointers point to it. That is why you get the same
results in second iteration.
You need to allocate space on the heap for those pointers (arrayA), for
example, in the first loop you could add something like
arrayA[i] = malloc(strlen(stations) + 1);
strcpy(arrayA[i], stations);
instead of
arrayA[i] = stations;
and in the second loop, after printing the value:
free(arrayA[i]);