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

前端 未结 4 1317
别那么骄傲
别那么骄傲 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:49

    What happens, is when you pass an array to a function, you only pass the address of the array in the memory, not the size of the array. What sizeof(buffer) is outputting in load_buffer() is the size of the pointer, which is four bytes.

    The best way to keep the size of the buffer in the function is to change the function to:

    void load_buffer(char *buffer, int length);
    

    and the call to:

    load_buffer(buffer, sizeof(buffer));
    

    and then use length whenever you want the size of buffer.

提交回复
热议问题