[英]How a function can set and get information from a struct in C
我编写了以下代码,我试图设置并通过get和set函数从结构中获取信息。 但是,当我编译并运行程序时,它不会显示从输入中获取的信息。 我的错在哪里?
#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;
}
你调用一个UB,因为_name
和_family
是指向你不拥有的内存的指针(因为你没有对它进行malloced
)
尝试将其更改为
typedef struct Information{
int _id;
char _name[SOME_SIZE_1];
char _family[SOME_SIZE_2];
}Information;`
或者,如果你想使用指针而不是数组,你应该在使用指针之前对它进行malloc,所以在你的set函数中,添加2个malloc语句:
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);
}
但是如果要分配内存,请不要忘记在完成后释放内存
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.