繁体   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