How a function can set and get information from a structure in C
I wrote the following code which I am trying to set and get information from the structure via get and set functions. However, when I compile and run the program, it does not display any information from the 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;
}
+3
user7619047
source
to share
1 answer
you are calling UB because _name
u _family
are pointers pointing to something you don't own (because you don't have 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 must malloc it before using 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, remember to free it when you are done
+11
source to share