我是C的新手。
我知道这是对的:
char* Str;
Str = (char*)calloc(Str_Len, sizeof(char));
,但为什么这不正确?
char* Str;
*Str = (char*)calloc(Str_Len, sizeof(char));
如何修改?感谢。
答案 0 :(得分:1)
首先是合法的,但C中的do not cast the return value of malloc
or calloc
(因为它们的返回类型为void *
)
在第二种情况下,Str
是char
类型,您无法为其分配更多1
字节的内存。此外,calloc
会返回pointer
,但*Str
的类型为char
。您无法将char *
数据类型分配给char
类型。
答案 1 :(得分:1)
实际上两者都不正确,因为不需要将C中的void*
转换为另一个
类型,它可以隐式转换。演员表本身并不是错误,但可能导致隐藏错误。
后者是错误的,因为*Str
取消引用指针(因此您访问char
),这不是指针类型,并且不能从指针分配。
答案 2 :(得分:0)
无论
char* Str;
Str = calloc(Str_Len, sizeof(char));
是否正确