如何使用malloc.h头分配内存到struct指针?

时间:2015-06-09 07:09:34

标签: c pointers malloc

#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编译器。

2 个答案:

答案 0 :(得分:6)

  

此代码有什么问题?

Ans:首先,你改变了#34;是&#34; &#34;是&#34;,两个主要问题,至少。让我详细说明一下。

  • 要点1.您将内存分配给指针,而不是指针的值。 FWIW,使用*c(即取消引用没有内存分配的指针)无效,将导致undefined behaviour

  • 第2点。请do not cast malloc()和C系列的返回值。您使用的演员绝对错误并证明第一个的真实性句。

要解决问题,请更改

*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()和家人,您不需要malloc.h头文件。这些函数是stdlib.h中的原型。

编辑:

建议:

  1. 在使用返回的指针之前检查malloc()是否成功。
  2. 使用结束后始终free()内存。
  3. main()的推荐签名为int main(void)

答案 1 :(得分:1)

这有效(在C和C ++上)。
由于您最初包含两个标记。

变化

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

c =(struct student*) malloc(sizeof(struct student));
相关问题