sizeof on argument

前端 未结 4 1822
感动是毒
感动是毒 2021-01-29 09:40

Even with int foo(char str[]); which will take in an array initialized to a string literal sizeof doesn\'t work. I was asked to do something like strlen and the app

相关标签:
4条回答
  • 2021-01-29 09:50

    You cannot pass an array as a function parameter, so you can't use the sizeof trick within the function. Array expressions are implicitly converted to pointer values in most contexts, including function calls. In the context of a function parameter declaration, T a[] and T a[N] are synonymous with T *.

    You'll need to pass the array size as a separate parameter.

    0 讨论(0)
  • 2021-01-29 09:52

    int foo(char str[]); will take in an array initialized to a string literal

    That's not what that does. char str[] here is identical to char* str. When an array type is used as the type of a parameter, it is converted to its corresponding pointer type.

    If you need the size of a pointed-to array in a function, you either need to pass the size yourself, using another parameter, or you need to compute it yourself in the function, if doing so is possible (e.g., in your scenario with a C string, you can easily find the end of the string).

    0 讨论(0)
  • 2021-01-29 09:55

    C strings are just arrays of char. Arrays are not passed by value in C; instead, a pointer to their first element is passed.

    So these two are the same:

    void foo(char blah[]) { ... }
    void foo(char *blah)  { ... }
    

    and these two are the same:

    char str[] = "Hello";
    foo(str);
    
    char *p = str;
    foo(p);
    
    0 讨论(0)
  • 2021-01-29 10:15

    You can't use sizeof here. In C arrays are decayed to pointers when passed to functions, so sizeof gives you 4 or 8 - size of pointer depending on platform. Use strlen(3) as suggested, or pass size of the array as explicit second argument.

    0 讨论(0)
提交回复
热议问题