[英]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: 意见建议:
malloc()
before using the returned pointer. malloc()
是否成功。 free()
the memory once the usage is over. free()
内存。 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.