简体   繁体   English

C 编程中的 Malloc - 不兼容的指针类型

[英]Malloc in C Programming - incompatible pointer types

What is the difference between ptr->Name = (struct rec*)malloc(sizeof(struct rec)); ptr->Name = (struct rec*)malloc(sizeof(struct rec)); 有什么区别? from ptr->Name = malloc(sizeof(struct rec));从 ptr->Name = malloc(sizeof(struct rec)); Why is it I'm receiving an error whenever I include (struct rec*) on malloc.为什么每当我在 malloc 上包含 (struct rec*) 时都会收到错误。

struct rec {
 char *Name;
}emp[100];

int main() {

int x;
int i;

struct rec *ptr = NULL;
ptr = emp;

printf("Enter Number of Clients: ");
scanf("%d", &x);
getchar();

for(i=0; i!=x; i++)
{
printf("Enter Name: ");
//I'm receiving an error whenever I add this
ptr->Name = (struct rec*)malloc(sizeof(struct rec));

//Code below is working
ptr->Name = malloc(sizeof(struct rec));

ptr->Name is of type char * . ptr->Namechar *类型。

ptr->Name = (struct rec*)malloc(sizeof(struct rec)) explicitly converts the return value from malloc() to a struct rec * . ptr->Name = (struct rec*)malloc(sizeof(struct rec))malloc()的返回值显式转换为struct rec * A struct rec * cannot be implicitly converted to a char * , so the assignment to ptr->Name is invalid. struct rec *不能隐式转换为char * ,因此对ptr->Name的赋值无效。

If there is a preceding #include <stdlib.h> in your code, ptr->Name = malloc(sizeof(struct rec)) works because malloc() return void * , and a void * can be implicitly converted to any pointer type, including to a char * .如果您的代码中有前面的#include <stdlib.h>ptr->Name = malloc(sizeof(struct rec))起作用,因为malloc()返回void * ,并且void *可以隐式转换为任何指针类型,包括到char * Without the preceding #include <stdlib.h> (or another header which provides a declaration of malloc() , the conversion is also invalid.如果没有前面的#include <stdlib.h> (或提供malloc()声明的另一个头文件,转换也是无效的。

void * is the ONLY pointer type in C that can be converted implicitly to another pointer type. void *是 C 中唯一可以隐式转换为另一种指针类型的指针类型。 Hence the difference between your two options.因此,您的两个选项之间存在差异。

The argument of malloc() is also wrong ie sizeof(struct rec) should not be used to dynamically allocate an array of char , in most circumstances. malloc()的参数也是错误的,即在大多数情况下,不应使用sizeof(struct rec)动态分配char数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM