簡體   English   中英

在C語言中將malloc與struct一起使用

[英]Using malloc with struct in C

所以,這是我的代碼:

#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為結構分配名稱? 錯誤是:

[錯誤]要求成員“名稱”使用非結構或聯合的名稱

sizeof*(struct person)是語法錯誤。 編譯器將其視為嘗試將sizeof運算符應用於*(struct person) 由於您不能取消引用類型,因此編譯器會抱怨。 我認為您打算編寫以下內容:

personPtr = malloc(sizeof *personPtr);

這是分配personPtr指向的內容的慣用方式。 現在,僅在定義指針的位置指定類型,這是一件好事。 您也不需要malloc轉換malloc的結果,因為void*可隱式轉換為任何指針類型。

第二個錯誤是雙重的:

  1. name是固定大小的數組。 您不能使用賦值運算符分配給數組。 您只能分配給每個單獨的元素。

  2. getchar返回單個字符,而不是您期望的字符串。 要讀取字符串,可以使用scanf("%17s", personPtr->name) 17是緩沖區的大小-1,以防止scanf在字符串中添加NUL終止符時防止緩沖區溢出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM