Search code examples
cpointersstructscanfnodes

Ask data from user and store them inside a struct in C


In the code below I tried to use printf and scanf to get data from user and store them inside a struct i defined called node.

The programme works fine for the first prompt, but as soon as the user input name, the programme ends with printing Age:salary:

Can anyone help me with this?

On a side note, can anyone also help me to understand how to create a loop to store data in various nodes and store them together? (Not hard-code it one by one)

Thank you very much!!

typedef struct node
{
    char *name;
    int age;
    int salary;
    struct node * next;
}node;

int main(void)
{
        node *tmp = malloc(sizeof(node));
        
        printf("Name:");
        scanf("%s", tmp->name);
        
        printf("Age:");
        scanf("%i", &(tmp->age));
        
        printf("salary:");
        scanf("%i", &(tmp->salary));
        
        tmp->next = NULL;
        
        free(tmp);
}


Solution

  • You are trying to write to Uninitialized memory

    This is a very common problem beginners face.

    You are trying to store the name using char *name declaration. Here name does not point to a valid memory location, that's why You program is not running as expected.

    Even if name points to a valid memory address, you must have enough memory allocated to store the data.

    You can use

    #define BUFFER_SIZE 50
    char name[BUFFER_SIZE];
    

    You can use any buffer size as you like, and then store a string of that length - 1 in the name array. -1 is for the null termination character \0.

    Using this declaration you are allocating memory of BUFFER_SIZE bytes and the name points to the first byte in that array.

    This allocation happens on the stack not in the HEAP