Error: Unhandled exception at 0x60092A8D (msvcr110d.dll) in C_Son60.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.
当执行以下代码时,会给出此错误代码。(编译成功) 我的错误在哪里?
#include <stdio.h>
int i;
int main(void){
char *names[3];
//get the names of the cities
puts("Enter names of cities");
for (i = 0; i < 3; i++)
{
fgets( names[i], 99, stdin);
}
//print entered names
for (i = 0; i < 3; i++)
{
printf("%s", *names[i]);
}
getch();
}
答案 0 :(得分:4)
在
中读取char指针之前,需要分配char指针所指向的内存例如:
for (i = 0; i < 3; i++)
{
names[i] = malloc(200);
fgets( names[i], 99, stdin);
}
答案 1 :(得分:2)
2件事:
malloc(100 * sizeof(char))
*names[i]
,即**(names + i)
。您需要的只是names[i]
使用代码:
#include <stdio.h>
int i;
int main(void){
char *names[3];
//get the names of the cities
puts("Enter names of cities");
for (i = 0; i < 3; i++)
{
names[i] = (char *)malloc(100 * sizeof(char));
fgets( names[i], 99, stdin);
}
//print entered names
for (i = 0; i < 3; i++)
{
printf("%s", names[i]);
}
getch();
}
答案 2 :(得分:1)