Filipe Canatto Filipe Canatto - 4 months ago 20
C Question

Uncertainty in a program using Struct and pointer (C language program)

Consider the following program:

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

int main()
{

typedef struct WFC_STRUCT {
int a;
int b;
} WFC_STRUCT;

WFC_STRUCT *ptr = (WFC_STRUCT*) NULL;

ptr->a=10;


return(0);

}


I would like to understand what is happening at instruction:

WFC_STRUCT *ptr = (WFC_STRUCT*) NULL;


Why the program is breaking? In what cases the instruction above is used?.

Answer
WFC_STRUCT *ptr = (WFC_STRUCT*) NULL; // cast is unnessesary
//moreover you have no memory alloacted

WFC_STRUCT *ptr = malloc(sizeof *ptr); // allocates memory, if this is done
//then you can do below
ptr->a=10;

Do check [ this ] answer on how to use pointers