我试图通过完成我在网上找到的随机项目来自学 C,但我遇到了一个小问题。目前正在学习指点。如何在 char 指针数组的索引处正确存储用户输入的值?
int i, numberPeople = 5;
char **firstName = (char**) malloc(numberPeople*sizeof(char));
char **lastName = (char**) malloc(numberPeople*sizeof(char));
double *scores = (double*) malloc(numberPeople*sizeof(double));
// allocating space for each individual person
for (i = 0; i < numberPeople; i++) {
firstName[i] = (char*) malloc(MAXIMUM_DATA_LENGTH*sizeof(char)); // MAXIMUM_DATA_LENGTH = 50
lastName[i] = (char*) malloc(MAXIMUM_DATA_LENGTH*sizeof(char));
scores[i] = *(double*) malloc(1*sizeof(double));
}
// begin user input for each person
for (i = 0; i < numberPeople; i++) {
printf("Person #%d \n\n", i + 1);
printf("First Name: ");
scanf("%s", firstName[i]);
printf("Last Name: ");
scanf("%s", lastName[i]); // crashes on person[2] ==> EXC_BAD_ACCESS (EXC_I386_GPFLT)
printf("Score: ");
scanf("%lf", &scores[i]);
printf("\n\n");
}
当我输入 person[2] 的姓氏时,我的程序总是停止/崩溃。显示的错误是 --> "EXC_BAD_ACCESS (EXC_I386_GPFLT)"。
最佳答案
这里,
char **firstName = (char**) malloc(numberPeople*sizeof(char));
char **lastName = (char**) malloc(numberPeople*sizeof(char));
你需要使用
char **firstName = (char**) malloc(numberPeople*sizeof(char *));
char **lastName = (char**) malloc(numberPeople*sizeof(char *));
因为你必须在 char 数组上存储一个指针数组。所以您的分配大小太小:sizeof(char)
为 1,您不能在 1 个字节上存储地址。
关于c - 在指针索引处存储值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36654309/