对于下面的 C 代码,当我只输入一个字符时,我希望最后一个 printf 打印“10,10”。相反,它打印“10,8”。为什么是input
当我 malloc 10 字节时只有 8 字节?
char* input;
unsigned long inputLen = 10;
input = (char*) malloc(10 * sizeof(char));
printf("Input: ");
getline(&input,&inputLen,stdin);
printf("%lu,%d",inputLen,sizeof(input));
最佳答案
sizeof(input)
返回指针input
的大小,即 8 个字节。
通过 C FAQ :
Q: Why doesn't
sizeof
tell me the size of the block of memory pointed to by a pointer?A:
sizeof
tells you the size of the pointer. There is no portable way to find out the size of amalloc
'ed block. (Remember, too, thatsizeof
operates at compile time, and see also question 7.27.)
如果你想跟踪input
的容量,你需要使用一个单独的变量,或者在堆栈上将input
声明为一个数组,然后将数组的大小除以数组中单个元素的大小。将容量保留为单独的变量几乎总是更容易。
关于c - C 中的 malloc() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41797365/