passing char buffer to functions and getting the size of the buffer

前端 未结 4 1395
别那么骄傲
别那么骄傲 2021-01-04 10:51

I have set the buffer to size 100. I display the buffer in the main function where the buffer is declared. However, when I pass the buffer to the function and get the sizeof

4条回答
  •  失恋的感觉
    2021-01-04 11:46

    The answers by Mitch Wheat and hhafez are completely right and to the point. I'm going to show some additional information which may prove useful sometimes.

    Note that the same happens if you tell the compiler that you have an array of the right size

    void load_buffer(char buffer[100]) {
        /* prints 4 too! */
        printf("sizeof(buffer): %d\n", sizeof(buffer));
    }
    

    An array as parameter is just declaring a pointer. The compiler automatically changes that to char *name even if it was declared as char name[N].

    If you want to force callers to pass an array of size 100 only, you can accept the address of the array (and the type of that) instead:

    void load_buffer(char (*buffer)[100]) {
        /* prints 100 */
        printf("sizeof(buffer): %d\n", sizeof(*buffer));
    }
    

    It's a pointer to the array you have in main, so you need to dereference in the function to get the array. Indexing then is done by

    buffer[0][N] or (*buffer)[N]
    

    Nobody I know is doing that and I'm neither doing it myself, because it rather complicates passing of the argument. But it's good to know about it. You can call the function like this then

    load_buffer(&buffer)
    

    If you want to accept other sizes too, i would go with the passing-N option the other two answers recommend.

提交回复
热议问题