I see that people often write C code such as:
char *ptr = malloc(sizeof(char)*256);
Is that really necessary? The standard says that sizeof(char)==1 by definition, so doesn’t it make sense just to write:
char *ptr = malloc(256);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, C defines
sizeof(char)to be 1, always (and C++ does as well).Nonetheless, as a general rule, I’d advise something like:
This way, when your boss says something like: “Oh, BTW we just got an order from China so we need to handle all three Chinese alphabets ASAP”, you can change it to:
and the rest can stay the same. Given that you’re going to have about 10 million headaches trying to handle i18n even halfway reasonably, eliminating even a few is worthwhile. That, of course, assumes the usual case that your
chars are really intended to hold characters — if it’s just a raw buffer of some sort, and you really want 256 bytes of storage, regardless of how many (of few) characters that may be, you should probably stick with themalloc(256)and be done with it.