Salmon Strikes
Salmon Strikes

Reputation: 43

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.

Upvotes: 3

Views: 1520

Answers (2)

Jared Beekman
Jared Beekman

Reputation: 320

If @abelenky answered your question fine, but I was always told to cast the results of malloc from the void * it returns into whatever you are actually working with.

mine *m = (mine *)malloc(sizeof(mine));

Upvotes: 0

abelenky
abelenky

Reputation: 64672

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!

Upvotes: 8

Related Questions