3 c struct pointers data-structures
我编写了以下代码,我试图设置并通过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;
}
Run Code Online (Sandbox Code Playgroud)
CIs*_*ies 11
你调用一个UB是因为_name&_family是指向你不拥有的内存的指针(因为你还没有malloced)
尝试将其更改为
typedef struct Information{
int _id;
char _name[SOME_SIZE_1];
char _family[SOME_SIZE_2];
}Information;`
Run Code Online (Sandbox Code Playgroud)
或者,如果你想使用指针而不是数组,你应该在使用指针之前对它进行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);
}
Run Code Online (Sandbox Code Playgroud)
但是如果要分配内存,请不要忘记在完成后释放内存