在指针索引处存储值?

时间:2016-04-15 18:22:01

标签: c pointers

我正在尝试通过完成我在网上找到的随机项目来教自己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]的lastName时,我的程序总是停止/崩溃。显示的错误是 - &gt; “EXC_BAD_ACCESS(EXC_I386_GPFLT)”

2 个答案:

答案 0 :(得分:2)

下面,

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个字节上存储地址。

答案 1 :(得分:0)

怎么样:

int i, numberPeople = 5;

char *firstName = malloc(numberPeople*sizeof(char));
char *lastName = malloc(numberPeople*sizeof(char));
double *scores = malloc(numberPeople*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]);

    printf("Score: ");
    scanf("%lf",&scores[i]);
    printf("\n\n");
}