Filling up array type char**

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.

My code is this>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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.
Last edited on
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.
Thanks for the answer. In the meantime, that occured to me so I tried doing like this>
1
2
3
4
5
6
7
8
9
if(strlen(line)>1)
        {
            words = temp;
            words[num] = malloc(sizeof(char)*strlen(line));  //allocating memory for each element
            words[num] = line;
            printf("%d - %s\n", num, words[num]);
            num++;
            temp = realloc(words, (num+1)*sizeof(char*));  //expanding array of arrays
        }


But the result is still the same.
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 
Yes! Now it works, thank you very much!
Topic archived. No new replies allowed.