如何使用 malloc.h header 为结构指针分配内存?
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 编译器。
What is the wrong with this code?
答:首先你把那个"is"改成"are",至少有两个主要问题。让我详细说明。
要点 1. 您将内存分配给指针,而不是分配给指针的值。 FWIW,使用 *c
(即,在没有内存分配的情况下取消引用指针)是无效的,将导致 undefined behaviour.
第2点。请do not castmalloc()
和C中家族的return值。你使用的演员是absolutely错了,证明第一句的真实性。
要解决问题,请更改
*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
.
编辑:
建议:
- 在使用 returned 指针之前检查
malloc()
是否成功。
- 使用结束后总是
free()
内存。
main()
的推荐签名是int main(void)
。
这有效(在 C 和 C++ 上)。
由于您最初包含了这两个标签。
改变
*c =(struct student)malloc(sizeof(struct student));
至
c =(struct student*) malloc(sizeof(struct student));
#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?
答:首先你把那个"is"改成"are",至少有两个主要问题。让我详细说明。
要点 1. 您将内存分配给指针,而不是分配给指针的值。 FWIW,使用
*c
(即,在没有内存分配的情况下取消引用指针)是无效的,将导致 undefined behaviour.第2点。请do not cast
malloc()
和C中家族的return值。你使用的演员是absolutely错了,证明第一句的真实性。
要解决问题,请更改
*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
.
编辑:
建议:
- 在使用 returned 指针之前检查
malloc()
是否成功。 - 使用结束后总是
free()
内存。 main()
的推荐签名是int main(void)
。
这有效(在 C 和 C++ 上)。
由于您最初包含了这两个标签。
改变
*c =(struct student)malloc(sizeof(struct student));
至
c =(struct student*) malloc(sizeof(struct student));