Hi..
I'm trying to set values of char** which I'm dynamically allocating. Everything seems to go well, but after the file i'm reading is finished, my array elements are all equal to the last word read.
int main ()
{
int i=0, j=0, num=0;
char c, line[256], **words, **temp;
words = (char**)malloc(sizeof(char*));
temp = words;
do {
c = fscanf(stdin,"%s",line);
if(strlen(line)>1)
{
words = temp;
words[num] = line;
//printf("%d - %s\n", num, words[num]); //here it works great
num+=1;
temp = (char**)realloc(words, (num+1)*sizeof(char*));
}
} while(c!=EOF);
printf("num: %d\n", num);
for(i = 0; i<20; i++)
printf("words: %s\n", words[i]); //here it just prints last word read for 20 times
free(words);
free(temp);
return 0;
}
EDIT: This is obviously C, I hope thats not a problem.
words[num] = line;Assign pointer words[num] to point to line.
As it points to line, all changes to line would be visible through this pointer too. http://puu.sh/kEWgP/5b13d6a68b.png
You need to allocate own storage for each element.
words[num] = malloc(sizeof(char)*strlen(line)); allocates memory and makes words[num] point to it. words[num] = line; points word[num] pointer to line, losing reference to allocated memory, leak.
You want to allocate memory and copy string to it:
1 2
words[num] = malloc(sizeof(char) * (strlen(line) + 1)); //Do not forget memory for null terminator.
strcpy(words[num], line); //Copy line in allocated memory