我正在使用动态内存分配编写此代码,对于学生记录如图所示,这段代码假设很简单,我显然是以正确的方式在正确的位置分配元素,但是当它打印它们时,它给了我一个“core dumped
”错误!怎么了?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char **firstname;
char **lastname;
float *score;
int number_of_records,i,j,ctr=1,row=15,col=20;
/*ctr is to keep track of the student's number (makes it easier to
the user), it starts with (1)*/
firstname=malloc(row*sizeof(char*));
for(i=0;i<row;i++)
{
firstname[i]=malloc((col+1)*sizeof(char));
}
lastname=malloc(row*sizeof(char*));
for(i=0;i<row;i++)
{
lastname[i]=malloc((col+1)*sizeof(char));
}
printf("\nPlease indicate number of records you want to enter (min 2, max 15): ");
scanf("%d",&number_of_records);
score=malloc(row*sizeof(float));
printf("\nPlease input records of students\n(enter a new line after"
"each record), with following format:\nfirst name last name score ");
for (i=0;i<number_of_records;i++)
{
printf("\nEnter record for student %d : ",ctr);
scanf("%s %s %f",firstname[i],lastname[i],score[i]);
ctr++; /*ctr is to keep track of student number
(makes it easy to the user) */
}
for (i=0;i<number_of_records;i++)
{
printf("%s %s %f\n",firstname[i],lastname[i],score[i]);
}
}
答案 0 :(得分:4)
请更改此内容:
for (i=0;i<number_of_records;i++)
{
printf("\nEnter record for student %d : ",ctr);
scanf("%s %s %f",&firstname[i],&lastname[i],&score[i]);
ctr++; /*ctr is to keep track of student number (makes it easy to the user) */
}
到这个
for (i=0;i<number_of_records;i++)
{
printf("\nEnter record for student %d : ",ctr);
scanf("%s %s %f",firstname[i],lastname[i],&score[i]);
ctr++; /*ctr is to keep track of student number (makes it easy to the user) */
}
它会起作用。原因是firstname[i]
和lastname[i]
已经pointers
;您不需要使用&
运算符。
P.S。此外,由于您使用的是C,请不要从malloc
或realloc
转换返回值。它将自动完成。