开发者

difference(s) between size_t and sizeof

What are the differences between,

malloc ( sizeof ( char ) * N ) 

and

size_t datalen = N 
malloc ( datalen  ) 

Where should we use size_t ins开发者_如何学编程tead of sizeof ( char ) and vice versa?

Are there any performance difference between size_t and sizeof ( char )?


size_t is an unsigned integer type guaranteed to support the longest object for the platform you use. It is also the result of the sizeof operator.
sizeof returns the size of the type in bytes.
So in your context of question in both cases you pass a size_t to malloc


That's like asking if there are performance differences between the literal 42 and the type int; they're different things.

You use sizeof(T) to get the number of bytes a T object uses. This is mainly useful for malloc/calloc/realloc.

You use size_t as the type to store that number.

size_t datalen = N * sizeof(char);
char* pBuf = malloc(datalen);


It does not literally return a value of type size_t since size_t is not a concrete type in itself, but rather a typedef to an unspecified built-in type. Typedef identifiers (such as size_t) are completely equivalent to their respective underlying types (and are converted thereto at compile time). If size_t is defined as an unsigned int on your platform, then sizeof returns an unsigned int when it is compiled on your system. size_t is just a handy way of maintaining portability and only needs to be included in stddef.h if you are using it explicitly by name.

This answer is a copy of this answer; it was originally written by user Volte.


In your example, the usefulness is neither particularly apparent nor compelling, and the question and code are flawed - what if the type were to change? datalen = N would be an inadequate size. There is a better idiom which makes better use of sizeof; sizeof(char) is pointless because by definition it is 1 (though CHAR_BIT need not be 8)

If the data type of the dynamic array were to change, and you allocated in blocks of sizeof(object) rather than sizeof(type) then your code becomes more easily maintainable.

e.g.

char* data = malloc(sizeof(*data) * N ) ;

then if you later decide that data should be int for example then:

int* data = malloc(sizeof(*data) * N ) ;

only one change instead of two (or many more every where else the size is needed). This is especially useful for structures and user defined types:

tSomeType* data = malloc(sizeof(*data) * N ) ;

where you might be changing the sizeof the type by adding or removing members for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜