Dynamic arrays in C without malloc?

前端 未结 4 509
不知归路
不知归路 2020-12-10 10:58

I\'ve always wondered how I could get away with this:

int main(int argc, char **argv) {
    printf(\"%p %s %d\\n\", &argv[1], argv[1], strlen(argv[1]));
         


        
4条回答
  •  不知归路
    2020-12-10 11:53

    "Variable length arrays" were added to the C language in C99. This is covered in §6.7.5.2 "Array declarators":

    If the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero. The size of each instance of a variable length array type does not change during its lifetime. Where a size expression is part of the operand of a sizeof operator and changing the value of the size expression would not affect the result of the operator, it is unspecified whether or not the size expression is evaluated.

提交回复
热议问题