Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating memory for array in struct (in C)

I need to define a type-struct in C that contains an array to be malloc'd as:

#include <stdio.h>
#include <stdlib.h>

typedef struct mine
{
    int N;
    double *A;
} mine;

int main(int argc, char** argv) 
{
    int i;
    mine *m=malloc(sizeof(mine));
    printf("sizeof(mine)=%d\n",sizeof(mine));
    scanf("Enter array size: %d",&(m->N));
    m->A=malloc((m->N)*sizeof(double));
    for(i=0; i < m->N; i++)
        m->A[i]=i+0.23;
    printf("First array element: %lf",m->A[0]);

    return (EXIT_SUCCESS);
}

The program compiles and runs, and the integer assignment seems to work fine. The array is not working as it should, however.

Any suggestions? I would like m to remain a pointer (to pass to functions etc.).

Thanks.

like image 510
Salmon Strikes Avatar asked Aug 25 '26 14:08

Salmon Strikes


1 Answers

This is your problem:

scanf("Enter array size: %d",&(m->N));

It should be two separate steps:

printf("Enter array size: ");
scanf("%d",&(m->N));

(and for debugging checking:)

printf("The size entered appears to be %d\n", m->N);

That way, you know if you got the value you intended to get!

like image 136
abelenky Avatar answered Aug 28 '26 05:08

abelenky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!