How a function can set and get information from a struct in C

c, data-structures, pointers, struct

Solution

you invoke an UB because `_name` & `_family` are pointers that point to memory you don't own (because you haven't `malloced` it)

try changing it to

typedef struct Information{
  int _id;
  char _name[SOME_SIZE_1];
  char _family[SOME_SIZE_2];
}Information;`

Or, if you want to stay with pointers instead of arrays, you should malloc it before using the pointers, so in your set function, add 2 malloc statements:

void setInformation(Information* arg_struct){
  arg_struct->_name = malloc(SOME_SIZE_1);
  arg_struct->_family = malloc(SOME_SIZE_2);
  printf("What is your name? ");
  scanf("%s %s", arg_struct->_name, arg_struct->_family);
  printf("What is your id? ");
  scanf("%d", &arg_struct->_id);
}

but if you are allocating memory, don't forget to free it when you are done

Problem

I written the following code which I am trying to set and to get information from a struct via get and set functions. However, when I compile and run the program it doesn't show the information which it gets from input. Where is my fault? ``` #include <stdio.h> #include <stdlib.h> typedef struct Information{ int _id; char* _name; char* _family; } Information; void setInformation(Information* arg_struct){ printf("What is your name? "); scanf("%s %s", arg_struct->_name, arg_struct->_family); printf("What is your id? "); scanf("%d", &arg_struct->_id); } void getInformation(Information* arg_struct){ printf("Your name is %s %s.\n", arg_struct->_name, arg_struct->_family); printf("Your id is %d.\n", arg_struct->_id); } int main(int argc, char const *argv[]){ Information *obj = malloc(sizeof(Information)); setInformation(obj); getInformation(obj); return 0; } ```

Original source