我已经为这段代码中的 char
指针分配了内存,我想检查它是否指向任何东西:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char *p = (char*) malloc(sizeof(char)*10);
if(*p == 0)
printf("The pointer points nothing !\n");
}
然后我检查了它是否没有指向任何内容。我还打印了指针的长度,它打印了“3”,尽管它什么也没打印。这是什么原因,我如何检查它是否没有任何意义?
最佳答案
您需要修改检查以检查返回的指针,而不是内容。有点像
if( p == NULL) {
fprintf(stderr, "The pointer points nothing !\n");
return 1;
}
应该做的。引用有关返回值的标准:
The
malloc
function returns either a null pointer or a pointer to the allocated space.
失败时返回空指针,否则返回的指针不等于空指针。
也就是说,
指向内存的初始内容是不确定的,不要尝试验证它。引用标准,
The
malloc
function allocates space for an object whose size is specified bysize
and whose value is indeterminate.这适用于您关于指针的“检查长度” 的其他问题 - 这是毫无意义的。除非您已将一些值存储(写入)到其中 - 尝试测量初始内容是没有意义的,因为它是不确定的。您最终可能会遇到 undefined behavior .
malloc()
和 family 对返回指针的转换是多余的。 It can be totally avoided in C.sizeof(char)
在 C 中保证为 1。因此,再次不需要使用sizeof(char)
作为乘数,< em>本身。
关于c - 分配后如何检查char指针是否指向任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53389371/