加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

函数如何在C中设置和获取结构中的信息

发布时间:2020-12-16 10:14:06 所属栏目:百科 来源:网络整理
导读:我编写了以下代码,我试图设置并通过get和set函数从结构中获取信息.但是,当我编译并运行程序时,它不会显示从输入中获取的信息.我的错在哪里? #include stdio.h#include stdlib.htypedef struct Information{ int _id; char* _name; char* _family;} Informat
我编写了以下代码,我试图设置并通过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->_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->_family);
  printf("What is your id? ");
  scanf("%d",&arg_struct->_id);
}

但是如果要分配内存,请不要忘记在完成后释放内存

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读