#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
中。
编辑:
建议:
- 在使用返回的指针之前检查
malloc()
是否成功。 - 总是在使用结束后
free()
内存。 main()
的推荐签名是int main(void)
。
关于c - 如何使用 malloc.h header 为结构指针分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30725202/