我想知道 sizeof(char) 和 sizeof(char *) 之间是否有区别:
char *s;
s = malloc(sizeof(char*)*len + 1);
char *s;
s = malloc(sizeof(char)*len + 1);
这是一样的吗?
最佳答案
char
是一个字符,sizeof(char)
定义为 1。(N1570 6.5.3.4 sizeof 和 _Alignof 运算符,第 4 段)
char*
是一个指向字符的指针,sizeof(char*)
取决于环境。在 32 位环境中通常为 4 个,在 64 位环境中通常为 8 个。
在 sizeof(char*) > sizeof(char)
的典型环境中,malloc(sizeof(char*)*len + 1)
将(至少尝试) 如果 len
足够小不会导致整数溢出,则分配比 malloc(sizeof(char)*len + 1)
更多的内存。
关于c - sizeof(char) 和 sizeof(char *) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40679801/