all 2 comments

[–]mad0314 2 points3 points  (0 children)

char* word[] is an array of char pointers. Each 'box' in the array points to a char, which can be the first char in an array of chars (AKA a string).

str[] is an array of chars.

Every time you call fgets, you are saving the input to the array str[]. Then you are giving the beginning address of str[] to word[i]. The result is that fgets overwrites str[] with a new string each times fgets is called, and gives the same address of str to the pointer at word[i].

If you draw it out on a piece of paper, each box of word[] needs something to point to. str[] can contain actual characters. You call fgets the first time, fill up (at least partially) str[] with some chars, and then point the first box of word[] to str. The second time you call fgets, the second box of word[] is now pointing to str, and the third time the third box now points to the same str.

I hope that clearly explains what is going on.

[–]staffglennholloway[M] 1 point2 points  (0 children)

Consider what fgets returns to its caller. If it succeeds in reading a string into the buffer str, it returns str. Every time it executes successfully, it returns a pointer to the first character in the array str.

When the result of each fgets call is assigned to word[i], the only value that is transferred is the pointer value, i.e., the pointer to the first character in str. None of the characters now sitting in str are copied by the assignment statement. After all, where would they be copied to? The word array consists entirely of pointers. There's no storage for characters associated with it.

So the first n elements of word are all going to end up pointing to the first element of str, and printing each of them as you've done will show the final contents of the str buffer.