简体   繁体   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;
}

What is the wrong with this code? 此代码有什么问题? I tried times by alternating this code to allocate memory to struct pointer. 我尝试通过交替这段代码来为结构指针分配内存来尝试多次。 But this error comes when compiling: 但是编译时会出现此错误:

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

I'm using mingw32 gcc compiler. 我正在使用mingw32 gcc编译器。

What is the wrong with this code? 此代码有什么问题?

Ans: First of all you change that "is" to "are", there are two major problems, atleast. 回答:首先,您将“是”更改为“是”,至少两个主要问题。 Let me elaborate. 让我详细说明。

  • Point 1. You allocate memory to the pointer , not to the value of pointer . 要点1.您将内存分配给指针 ,而不是指针 FWIW, using *c (ie, de-referencing the pointer without memory allocation) is invalid and will result in undefined behaviour . FWIW使用*c (即在没有分配内存的情况下取消引用指针)是无效的,并且将导致未定义的行为

  • Point 2. Please do not cast the return value of malloc() and family in C. The cast you used is absolutely wrong and proves the authenticity of the first sentence. 要点2。请不要在C中malloc()和family的返回值。您使用的强制转换是绝对错误的,并证明了第一句话的真实性。

To solve the issues, change 解决问题,改变

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

to

c = malloc(sizeof(struct student));

or, for better, 或者,更好的是

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

Also, please note , to make use of malloc() and family , you don't need the malloc.h header file. 另外,请注意 ,要使用malloc()和family,则不需要malloc.h头文件。 These functions are prototyped in stdlib.h . 这些函数在stdlib.h中原型化。


EDIT: 编辑:

Suggestions: 意见建议:

  1. Check for success of malloc() before using the returned pointer. 在使用返回的指针之前,请检查malloc()是否成功。
  2. Always free() the memory once the usage is over. 使用结束后,请始终free()内存。
  3. The recommended signature of main() is int main(void) . 推荐的main()签名是int main(void)

This worked (on C and C++). 这工作(在C和C ++上)。
Since you originally included both tags. 由于您最初同时包含了两个标签。

change 更改

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM