#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char* string;
int main(void)
{
char *names[6];
int num_entries = 0,i=0,size=0;
string name = (string) malloc(sizeof(char) * 16);
printf("\nHow many names do you want to enter ? \n");
scanf("%d",&num_entries);
for(i=0 ; i < num_entries ; i++)
{
printf("\nEnter a name : ");
gets(name);
size = strlen(name);
names[i] = (string) malloc(sizeof(char)*size + 1);
strcpy(names[i],name);
}
for(i=0 ; i < num_entries ; i++)
puts(names[i]);
}
第一次在这个程序中的字符串没有被读取周围循环的第一时间,但是能正常工作的所有后续调用,程序只需简单的接受N个字符串,存储和显示他们。但它执行n-1次。解决方案也可以随意指出指针,分配等方式中的任何错误,任何反馈都会被赞赏。字符串没有被读取周围
'gets()'是邪恶的。考虑使用'fgets()'来代替。查看本页底部附近的BUGS部分:http://manpages.debian.net/cgi-bin/man.cgi?query=fgets&apropos=0&sektion=0&manpath=Debian+7.0+wheezy&format=html&locale=en – alk
更改了获取()调用fgets(name,16,stdin)仍然是bug – rootavish
@alk只是对改进做出评论,而不是提供对问题的回答。这就是为什么它是评论,而不是答案。 :)这是另一个评论:因为你总是设置它们,所以你的整数预初始化程序是多余的。 :) – lurker