【发布时间】:2016-04-30 16:57:57
【问题描述】:
我想将 5 个书名中的每一个存储在数组中并打印出来。但是我在这里做错了什么? 输出将最后一个条目打印 5 次。
#include <stdio.h>
int main(int argc, const char * argv[])
{
char * books[5];
char currentBook[1024];
for(int i = 0; i < 5; i++)
{
printf("Enter book:\n");
gets(currentBook);
books[i] = currentBook;
}
for(int i = 0; i <5; i ++)
{
printf("Book #%d: %s\n", i, books[i]);
}
}
【问题讨论】:
-
永远不要使用
gets。它本质上是不安全的。 -
您将
currentBook的地址存储在每个数组元素中,其中包含最新条目。我建议books[i] = strdup(currentBook);,然后你必须free数组中的每个指针,因为strdup从malloc获取内存。
标签: c loops pointers unix char