sizeof(char)和sizeof(char *)之间的区别 [英] Difference between sizeof(char) and sizeof(char *)
问题描述
我想知道sizeof(char)和sizeof(char *)之间是否有区别:
I'm wondering if there is a difference between sizeof(char) and sizeof(char *) :
char *s;
s = malloc(sizeof(char*)*len + 1);
char *s;
s = malloc(sizeof(char)*len + 1);
是不是一样?
推荐答案
char
is a character and sizeof(char)
is defined to be 1. (N1570 6.5.3.4 The sizeof and _Alignof operators, paragraph 4)
char*
是指向字符的指针,而sizeof(char*)
取决于环境.在32位环境中通常为4,而在64位环境中通常为8.
char*
is a pointer to a character and sizeof(char*)
depends on the environment. It is typically 4 in 32-bit environment and 8 in 64-bit environment.
在sizeof(char*) > sizeof(char)
的典型环境中,如果len
足够小而不会引起整数溢出,则malloc(sizeof(char*)*len + 1)
将(至少尝试)分配比malloc(sizeof(char)*len + 1)
更多的内存.
In typical environment where sizeof(char*) > sizeof(char)
, malloc(sizeof(char*)*len + 1)
will (at least try to) allocate more memory than malloc(sizeof(char)*len + 1)
if len
is small enough not to cause integer overflow.
这篇关于sizeof(char)和sizeof(char *)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!