Search code examples
carraysdouble-pointer

What is the cause of pointer alighnment issue?


My program reads words from a file, and stores them in a dynamically allocated array as a number of words.

My problem is while in the while loop when I print the array, it seems to pointing to the correct word. After the code falls through the while loop, when I print all the indicies, 'ice' is the last word, and I am trying to find out why.

FILE *fileptr=fopen("file.txt","r");

char** DataArray;
int num_of_words=0;

char str[10];

while(fscanf(fileptr,"%s",&str)!=-1)
{
    num_of_words++;
}

DataArray=(char**)malloc(num_of_words*sizeof(char*));

rewind(fileptr);

int i=0;

while(fscanf(fileptr,"%s",&str)!=-1)
{
    printf("%s",str);
    int len=strlen(str);
    printf("\t%d",len);

    DataArray[i]=(char*)malloc(len*sizeof(char));
    DataArray[i]=str;
    printf("\t%s\n",DataArray[i]);
    i++;
}

printf("\n");
//printf("%s\n",*(DataArray+2));
printf("%s\n",DataArray[0]);
printf("%s\n",DataArray[1]);
printf("%s\n",DataArray[2]);


fclose(fileptr);

Output:

apple  5   apple
mango  5   mango
ice  3   ice

ice
ice
ice

Solution

  • It's not enough to assign a pointer. Especially when str takes on a new value each time through the loop.

    DataArray[i]=(char*)malloc(len*sizeof(char));
    DataArray[i]=str;
    printf("\t%s\n",DataArray[i]);
    i++;
    

    You have to use strcpy the way you have written this program, because you have already allocated space using malloc. You can also use strdup, but that creates the dynamic storage for you. If it were up to me, I'd write it the way you have written it, using malloc first, and then

    strcpy(DataArray[i], str);