Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find sizeof char array C++

Tags:

c++

sizeof

im trying to get the sizeof char array variable in a different function where it was initialize however cant get the right sizeof. please 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;
}

the output is:

sizeof: 4
sizeof after foo(): 13

desired output is:

sizeof: 13
sizeof after foo(): 13
like image 378
Carlitos Overflow Avatar asked Nov 25 '11 19:11

Carlitos Overflow


1 Answers

This can't be done with pointers alone. Pointers contain no information about the size of the array - they are only a memory address. Because arrays decay to pointers when passed to a function, you lose the size of the array.

One way however is to use templates:

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

You can then call the function like this (just 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
like image 83
Marlon Avatar answered Oct 01 '22 10:10

Marlon