I have a quick question about the C sizeof() function. I'm passing an array into a function, and inside that function, I want to check the size of the array. However, regardless of the size of the input array, inside the function, it always seems to have a size of 4. For example:
void checkArraySize(char data[])
{
int internalSize = sizeof(data); //internalSize is reported as 4
}
void main(void)
{
char data[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
int externalSize = sizeof(data); //externalSize is reported as 8
checkArraySize(data);
}
As the comments in the code state, before I call a function like checkArraySize(), I check the size of the array, and it shows 8. However, when I check the size of the array inside the function, it only reports as having 4 elements (it reports 4 elements regardless of the size of the input array).
More often than not, when I see issues like this, it's because there is a gap in my understanding of the topic. So, I'm sure I'm just missing something with how passing arrays works. If not, any ideas as to why this is happening?
Note: This is on a PIC32, so I'm using Microchip's MPLAB X IDE and XC32 compiler.
Array in C always passed by reference. Thats why you are getting pointer size each time, not actual size.
To work with array in C as an argument, you should pass size of array with array.
I modified your program to working condition:
passed by reference means only address of first element of array is sent. If you change anything even inside function checkArraySize, this change would be reflected to original array too. Check modified above example.
output would be: