【问题标题】:Using malloc with struct in C在 C 中使用带有结构的 malloc
【发布时间】:2017-01-19 08:15:36
【问题描述】:

所以,这是我的代码:

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>

struct person{
    char name[18];
   int age;
   float weight;
};

int main()
{
    struct person *personPtr=NULL, person1, person2;
    personPtr=(struct person*)malloc(sizeof*(struct person));
    assert (personPtr!=NULL);
    personPtr = &person1;                   // Referencing pointer to memory address of person1

    strcpy (person2.name, "Antony");                //chose a name for the second person
    person2.age=22;                                 //The age of the second person
    person2.weight=21.5;                                //The weight of the second person


    printf("Enter a name: ");               
    personPtr.name=getchar();                   //Here we chose a name for the first person

    printf("Enter integer: ");              
    scanf("%d",&(*personPtr).age);          //Here we chose the age of the first person

    printf("Enter number: ");               
    scanf("%f",&(*personPtr).weight);       //Here we chose the weithgt of the first person

    printf("Displaying: ");                                             //Display the list of persons
    printf("\n %s, %d , %.2f ", (*personPtr).name, (*personPtr).age,(*personPtr).weight);           //first person displayed
    printf("\n %s, %d , %.2f",person2.name, person2.age, person2.weight);                       //second person displayed
    free(personPtr);
    return 0;
}

我收到两个错误,但我不知道为什么。首先,我认为我没有正确分配内存,第一个错误在下一行:

personPtr=(struct person*)malloc(sizeof*(struct person));

上面写着:

[错误] ')' 标记之前的预期表达式

我得到的第二个错误在线

personPtr.name=getchar();

为什么我不能使用 getchar 为结构分配名称?错误是:

[错误] 在非结构或联合的内容中请求成员“名称”

【问题讨论】:

  • personPtr=malloc(sizeof(struct person));personPtr-&gt;name[0]=getchar();

标签: c pointers structure


【解决方案1】:

sizeof*(struct person) 是语法错误。编译器将其视为将sizeof 运算符应用于*(struct person) 的尝试。由于您不能取消引用类型,因此编译器会抱怨。我认为您的意思是写以下内容:

personPtr = malloc(sizeof *personPtr);

这是分配personPtr 指向的任何东西的惯用方式。现在只在定义指针的地方指定类型,这是一件好事。您也不需要转换malloc 的结果,因为void* 可以隐式转换为任何指针类型。

第二个错误是双重的:

  1. name 是一个固定大小的数组。您不能使用赋值运算符分配给数组。您只能分配给每个单独的元素。

  2. getchar 返回单个字符,而不是您期望的字符串。要读取字符串,可以使用scanf("%17s", personPtr-&gt;name)。 17 是缓冲区的大小 - 1,用于在 scanf 将 NUL 终止符添加到字符串时防止缓冲区溢出。

【讨论】:

  • 即使我使用 scanf 仍然会出错:[错误] 格式 '%s' 需要 'char ' 类型的参数,但参数 2 的类型为 'char ( )[18]' .. 另一方面,如果我从 scanf 中删除 & 程序运行.. 但它结束后给我一个错误
  • @NeacsuMihai - 你是对的。我在匆忙中打错了。现在修好了。 name 是一个数组,将衰减为正确的指针类型。不需要&amp;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 2014-04-07
  • 2012-10-02
相关资源
最近更新 更多