c - 如何使用 malloc.h header 为结构指针分配内存?

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

最佳答案

What is the wrong with this code?

Ans:首先你把“is”改成“are”,至少有两个主要问题。让我详细说明。

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

  • 第2点。请do not cast malloc() 的返回值和 C 中的 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 头文件。这些函数的原型(prototype)在 stdlib.h 中。


编辑:

建议:

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

关于c - 如何使用 malloc.h header 为结构指针分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30725202/

相关文章:

C 读取文件并从输出中删除字符,无数组

c++ - const char * 数组中的元素数

c - 分配一个结构并在其中保存一个字符串

c - 我如何使用 malloc 在 C 中创建矩阵并避免内存问题?如何使用 C99 语法将矩阵传递给函数?

c - openssl中 `aes.h`函数的实现

c - 使用wordexp时保留引号

c++ - 为什么在这种情况下需要指针?

c++ - 如何在不知道其父节点的情况下旋转子树

c - 反对 free_if_heap(void *ptr)?

c - BST 插入不工作