Carlitos Overflow
Carlitos Overflow

Reputation: 683

find sizeof char array C++

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

Upvotes: 5

Views: 3853

Answers (3)

Marlon
Marlon

Reputation: 20314

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

Upvotes: 15

Loki Astari
Loki Astari

Reputation: 264331

Some template magic:

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

Upvotes: 1

Adrian Cornish
Adrian Cornish

Reputation: 23848

You cant. In foo you are asking for the size of a "uint8_t pointer". Pass the size as a separate parameter if you need it in foo.

Upvotes: 5

Related Questions