Is it necessary to multiply by sizeof( char ) when manipulating memory?

后端 未结 8 1135
走了就别回头了
走了就别回头了 2021-01-01 22:26

When using malloc and doing similar memory manipulation can I rely on sizeof( char ) being always 1?

For example I need to allocate memory for N elements of type

8条回答
  •  温柔的废话
    2021-01-01 22:34

    I consider it kind of an anti-pattern. It signals that the programmer didn't quite know what he/she was doing, which immediately casts the rest of the code in dubious light.

    Granted, it's not (quoting Wikipedia) "ineffective", but I do find it "far from optimal". It doesn't cost anything at run-time, but it clutters the code with needless junk, all the while signalling that someone thought it necessary.

    Also, please note that the expression doesn't parse as a function-call: sizeof is not a function. You're not calling a function passing it the magical symbol char. You're applying the built-in unary prefix operator sizeof to an expression, and your expression is in this case a cast to the type char, which in C is written as (char).

    It's perfectly possible, and highly recommended whenever possible, to use sizeof on other expressions, it will then yield the size of the expression's value:

    char a;
    printf("A char's size is %u\n", (unsigned int) sizeof a);
    

    This will print 1, always, on all conforming C implementations.

    I also heavily agree with David Cournapeau and consider repeating the type name in a malloc()-call to also be kind of an anti-pattern.

    Instead of

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

    that many would write to allocate an N-character-capacity string buffer, I'd go with

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

    Or (for strings only) omit the sizeof as per above, but this of course is more general and works just as well for any type of pointer.

提交回复
热议问题