Find sizeof char array C ++

im trying to get the sizeof char array variable in another function where it was initialized but cannot get the correct sizeof. see code below

int foo(uint8 *buffer){ cout <<"sizeof: "<< sizeof(buffer) <<endl; } int main() { uint8 txbuffer[13]={0}; uint8 uibuffer[4] = "abc"; uint8 rxbuffer[4] = "def"; uint8 l[2]="g"; int index = 1; foo(txbuffer); cout <<"sizeof after foo(): " <<sizeof(txbuffer) <<endl; return 0; } 

output:

 sizeof: 4 sizeof after foo(): 13 

desired result:

 sizeof: 13 sizeof after foo(): 13 
+4
source share
3 answers

This cannot be done with pointers only. Pointers do not contain information about the size of the array - they are only a memory address. Since arrays break up into pointers when passing a function, you lose the size of the array.

One way is to use templates:

 template <typename T, size_t N> size_t foo(const T (&buffer)[N]) { cout << "size: " << N << endl; return N; } 

Then you can call a function like this (like any other function):

 int main() { char a[42]; int b[100]; short c[77]; foo(a); foo(b); foo(c); } 

Output:

 size: 42 size: 100 size: 77 
+14
source

You can not. In foo, you request the size of the "uint8_t pointer". Pass size as a separate parameter if you need it in foo.

+5
source

Some magic pattern:

 template<typename T, size_t size> size_t getSize(T (& const)[ size ]) { std::cout << "Size: " << size << "\n"; return size; } 
+1
source

Source: https://habr.com/ru/post/1383120/


All Articles