![](/img/trans.png)
[英]What is the difference between using malloc to allocate memory to a struct pointer and pointing a struct pointer to a struct's memory address?
[英]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编译器。
此代码有什么问题?
回答:首先,您将“是”更改为“是”,至少有两个主要问题。 让我详细说明。
要点1.您将内存分配给指针 ,而不是指针的值 。 FWIW使用*c
(即在没有分配内存的情况下取消引用指针)是无效的,并且将导致未定义的行为 。
要点2。请不要在C中malloc()
和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
头文件。 这些函数在stdlib.h
中原型化。
编辑:
意见建议:
malloc()
是否成功。 free()
内存。 main()
签名是int main(void)
。 这工作(在C和C ++上)。
由于您最初同时包含了两个标签。
更改
*c =(struct student)malloc(sizeof(struct student));
至
c =(struct student*) malloc(sizeof(struct student));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.