如何在C中实现动态数组?

问题描述 投票:0回答:1

我正在使用动态内存分配编写这段代码,对于所示的学生记录,这段代码应该很简单,我显然是以正确的方式将元素分配在正确的位置,但是当涉及到打印它们时,它给了我一个“

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]);
    }
}
c dynamic-arrays dynamic-allocation
1个回答
4
投票

这里曾经有答案,但被遗忘了

© www.soinside.com 2019 - 2024. All rights reserved.