I'm trying to allocate memory for an array inside a struct like this one:
typedef struct
{
int a;
int *b;
} MyStruct;
I have a function to initialize the struct like this one:
void init( MyStruct * myStruct, int size )
{
myStruct = malloc( sizeof( MyStruct ) );
myStruct->a = size;
myStruct->b = malloc( size * sizeof( int ) );
}
But when I try to allocate memory for the fields inside the array b, I get the segmentation fault error
int main( void )
{
int i, size = 5;
MyStruct *myStruct;
init( myStruct, size );
for( i = 0; i < size; i++ )
{
myStruct->b[i] = malloc( sizeof( int ) ); //fails here
myStruct->b[i] = i*i;
}
}
I tried searching over and over, but I was not able to solve this problem. Someone knows why this is happening?