Miral Miral - 1 year ago 57
C Question

pass scanf value to struct pointer Segmentation Fault

All I want to do is a basic printing with a struct pointer using user input. I got a

segmentation fault
when I try to do with below code. I'm new to c, thanks anyway.

typedef struct {
int *licenseNum;
char *name;
char *region;
} City;

typedef struct {
struct Node *current;
struct Node *head;
struct Node *tail;
struct Node *next;
struct Node *secondNext;
City *data;
} Node;

int main()
Node *node = malloc(sizeof(Node));
City *city = malloc(sizeof(City));
puts("License number of the City: ");
scanf("%d", &(node -> data -> licenseNum));
printf("%d", node -> data -> licenseNum);
return 0;

Answer Source

You didn't set data in node.

Node * node = malloc(sizeof(Node));
City * city = malloc(sizeof(City));
// node->data is not yet defined!
// It has a random value! You must first initialize it:
node->data = city;

Also you shouldn't use malloc here as memory allocated by malloc has random values. Only use malloc if you for sure initialize all the pointers in a struct with meaningful values prior to using them. It's much safer to use calloc:

Node * node = calloc(1, sizeof(Node));
City * city = calloc(1, sizeof(City));
node->data = city;

calloc works like malloc, but it guarantees that the returned memory is all set to zero (all int values are 0, all pointers are NULL). The first argument of calloc (1 in the code above) is the number of items you want to allocate, here it is just one. E.g. calloc(5, sizeof(City)) would allocate memory for 5 cities in a single block, e.g.:

Cities * cities = calloc(5, sizeof(City));
cities[0].name = "New York";
cities[1].name = "London";
// ... and so on
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download