这非常奇怪 - 我从文件中获取行,将它们打印到屏幕上,并将它们存储在数组中。 将它们打印到屏幕上时,一切看起来都很好,但在数组中,每个元素都设置为文件的最后一行。
文件看起来像这样:
DarkMatter Fire Water Air Earth Plasma Wind这是我的代码:
char *rooms[7]; FILE *roomFile = fopen("rooms.txt", "r"); char name[20]; for(i=0; i<7; i++) { fgets(name, sizeof name, roomFile); rooms[i] = name; printf("%s", rooms[i]); } for(i=0; i<7; i++) { printf("%s\n", rooms[i]); }在文件循环中打印rooms[i]时,一切看起来都很好,但是一旦我尝试打印房间数组后,每个元素都会被设置为wind 。 这怎么可能?
输出:
DarkMatter Fire Water Air Earth Plasma Wind Wind Wind Wind Wind Wind Wind WindThis is incredibly strange - I'm getting the lines from a file, printing them out to the screen, and storing them in array. When printing them out to the screen everything looks fine, but in the array every element is set to the last line of the file.
File looks like this:
DarkMatter Fire Water Air Earth Plasma WindThis is my code:
char *rooms[7]; FILE *roomFile = fopen("rooms.txt", "r"); char name[20]; for(i=0; i<7; i++) { fgets(name, sizeof name, roomFile); rooms[i] = name; printf("%s", rooms[i]); } for(i=0; i<7; i++) { printf("%s\n", rooms[i]); }When printing rooms[i] during the file loop everything looks fine, but once I try to print the rooms array afterwards, every element is set to wind. How is this even possible?
Output:
DarkMatter Fire Water Air Earth Plasma Wind Wind Wind Wind Wind Wind Wind Wind最满意答案
更换
rooms[i] = name;同
//rooms[i] = name; rooms[i] = malloc(20); strcpy(rooms[i], name);原因
声明rooms[i] = name; 只是指示指针rooms[i]等于指针(或数组) name 。 所以有效的每个rooms[0], rooms[1], rooms[2]包含name的地址。 在for循环的每次迭代中, name都被复制为不同的字符串。 但是由name指出的地址,因此rooms所有元素都保持不变。
Replace
rooms[i] = name;with
//rooms[i] = name; rooms[i] = malloc(20); strcpy(rooms[i], name);Reason
The statement rooms[i] = name; simply instructs that the pointer rooms[i] is equal to the pointer (or array) name. So effectively each of rooms[0], rooms[1], rooms[2] holds the address of name. In each iteration of your for loop, name gets copied with a different string. But the address pointed to by name and hence all the elements of rooms remain the same.
更多推荐
发布评论