It is necessary to pass an array to the function and determine the size of the array inside the function. I try to do this:

#include <stdio.h> void pass(int buf[256]) { printf("size is %d\n", sizeof(buf)); } void main() { int buf[256]; pass(buf); } 

and get when printing

size is 4

How to transfer the size of the array correctly and why, as I do, it is not transmitted?

  • With this writing, it is not necessary to “recognize” the size of the buffer, it is already set for you - this number is 256. - IAZ

4 answers 4

And how do you imagine it works? The function actually receives the address of an array of numbers at the input .. one address and nothing else. In order to transfer the size of the array, you must transfer it .. literally. For example, so

 void pass(int * buff, int buffer_size) { printf("size is %d\n", buffer_size); } 

    In C ++, you can do this:

     template<size_t size> void pass(int (&buf)[size]) { printf("size is %d\n", size); } 
       double mean(int n, double *a) 

      where n is the number of elements in the array

        and it may be more correct to use sizeof without brackets, like this:

         void pass (int buf[]) { printf("size of buffer is %d\n", sizeof buf); } 
        • Maybe more correctly, but not on C! - IAZ