[英]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.