5

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

3 Answers 3

15

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
Sign up to request clarification or add additional context in comments.

2 Comments

@Marlon im new to templates in C++, so how i should call function foo?, an example would be appreciated.
@Marlon how about adding function foo() and template to the header file?
5

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.

Comments

1

Some template magic:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.