cdynamic-arraysdynamic-allocation

How to implement dynamic arrays in C?


I am writing this code using dynamic memory allocation, for student records as indicated, this code suppose to be simple , I am obviously allocating elements in their correct places the right way, but when it comes to printing them, it gives me a "core dumped" error ! what is wrong ?

#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]);
    }
}

Solution

  • Please change this:

    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) */
        }
    

    to this

    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) */
        }
    

    And it will work. The reason is that firstname[i] and lastname[i] are already pointers; you do not need to use & operator for them.

    P.S. Also, since you are using C, do no cast the returning values from malloc or realloc. It will be done automatically.