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.
malloc(sizeof(mine));- rathermalloc(sizeof(*m));; 2.&(m->N)- try&m->Ninstead; 3.printf("sizeof(mine)=%d\n",sizeof(mine));is UB, use the%zuformat specifier and look up what's they type of the valuesizeof()yields; 4.m->A=malloc((m->N)*sizeof(double));- some whitespace, readability and safety doesn't hurt, writem->A = malloc(m->N * sizeof(m->A[0]));instead.scanfdoesn't take a "prompt" string. Always check it's return value before using its outputs!sizeof(*m)is safer thansizeof(mine))in case decide to change the type ofmfromminetoyours.