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

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

    From the OP

    void load_buffer(char *buffer)
    {
        printf("sizeof(buffer): %d\n", sizeof(buffer));
    }
    

    Even though you can imagine that load_buffer() is passed the buffer by refrence, what is really happening is you are passing a pointer to char by value. The actual array is not passed so there is no way for the load_buffer() function to know the size of the buffer array

    So what is sizeof(buffer) doing? It is simply returning the size of a pointer to char. If load_buffer() needs the size of the buffer it needs to be passed speratly.

    Or you can create a new struct that contains both a char array and the size of the array, and pass a pointer to that struct instead, that way the buffer and it's size are always together ;)

提交回复
热议问题