我对C相当陌生,在引用字符串时遇到了数组和指针。我可以要求输入2个数字(整数),然后返回我想要的数字(第一个数字或第二个数字),没有任何问题。但是,当我请求名称并尝试返回它们时,程序在输入名字后崩溃,但不知道为什么。指针和malloc问题
从理论上讲,我希望为第一个名字保留内存,然后将其扩展为包含第二个名称。任何人都可以解释为什么这打破
谢谢!
#include <stdio.h>
#include <stdlib.h>
void main()
{
int NumItems = 0;
NumItems += 1;
char* NameList = malloc(sizeof(char[10])*NumItems);
printf("Please enter name #1: \n");
scanf("%9s", NameList[0]);
fpurge(stdin);
NumItems += 1;
NameList = realloc(NameList,sizeof(char[10])*NumItems);
printf("Please enter name #2: \n");
scanf("%9s", NameList[1]);
fpurge(stdin);
printf("The first name is: %s",NameList[0]);
printf("The second name is: %s",NameList[1]);
return 0;
}
你不能有一个`void`函数返回0;但是`main()`应该总是首先声明返回`int`。 – 2011-02-12 22:54:15
谢谢乔纳森。我做了这个改变。 – Andy 2011-02-12 23:09:56