【问题标题】:How a function can set and get information from a struct in C函数如何从 C 中的结构中设置和获取信息
【发布时间】:2017-10-13 04:02:24
【问题描述】:

我编写了以下代码,我试图设置并通过 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;
}

【问题讨论】:

    标签: c pointers data-structures struct


    【解决方案1】:

    您调用 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);
    }
    

    但是如果你正在分配内存,别忘了在完成后释放它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2022-07-18
      相关资源
      最近更新 更多