簡體   English   中英

如何使用malloc.h標頭將內存分配給結構指針?

[英]How to allocate memory to struct pointer using malloc.h header?

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

struct student
{
    char name[25];
    int age;
};

int main()
{
    struct student *c;

    *c =(struct student)malloc(sizeof(struct student));
    return 0;
}

此代碼有什么問題? 我嘗試通過交替這段代碼來為結構指針分配內存來嘗試多次。 但是編譯時會出現此錯誤:

testp.c:15:43: error: conversion to non-scalar type requested
  *c =(struct student)malloc(sizeof(struct student));
                                           ^

我正在使用mingw32 gcc編譯器。

此代碼有什么問題?

回答:首先,您將“是”更改為“是”,至少兩個主要問題。 讓我詳細說明。

  • 要點1.您將內存分配給指針 ,而不是指針 FWIW使用*c (即在沒有分配內存的情況下取消引用指針)是無效的,並且將導致未定義的行為

  • 要點2。請不要在C中malloc()和family的返回值。您使用的強制轉換是絕對錯誤的,並證明了第一句話的真實性。

解決問題,改變

*c =(struct student)malloc(sizeof(struct student));

c = malloc(sizeof(struct student));

或者,更好的是

c = malloc(sizeof*c);   //yes, this is not a multiplication
                        //and sizeof is not a function, it's an operator

另外,請注意 ,要使用malloc()和family,則不需要malloc.h頭文件。 這些函數在stdlib.h中原型化。


編輯:

意見建議:

  1. 在使用返回的指針之前,請檢查malloc()是否成功。
  2. 使用結束后,請始終free()內存。
  3. 推薦的main()簽名是int main(void)

這工作(在C和C ++上)。
由於您最初同時包含了兩個標簽。

更改

*c =(struct student)malloc(sizeof(struct student));

c =(struct student*) malloc(sizeof(struct student));

暫無
暫無

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

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