Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this possible? [pointer to char array C]

Is this possible?

size_t calculate(char *s)
{
    // I would like to return 64
}

int main()
{
    char s[64];

    printf("%d", calculate(s));

    return 0;
}

I want to write a function which calculates the size of the char array declared in main().

like image 514
Ulrira Avatar asked Feb 27 '26 03:02

Ulrira


1 Answers

Your function calculate(), given just the pointer argument s, cannot calculate how big the array is. The size of the array is not encoded in the pointer, or accessible from the pointer. If it is designed to take a null-terminated string as an argument, it can determine how long that string is; that's what strlen() does, of course. But if it wants to know how much information it can safely copy into the array, it has to be told how big the array is, or make an assumption that there is enough space.

As others have pointed out, the sizeof() operator can be used in the function where the array definition is visible to get the size of the array. But in a function that cannot see the definition of the array you cannot usefully apply the sizeof() operator. If the array was a global variable whose definition (not declaration) was in scope (visible) where calculate() was written - and not, therefore, the parameter to the function - then calculate() could indicate the size.

This is why many, many C functions take a pointer and a length. The absence of the information is why C is somewhat prone to people misusing it and producing 'buffer overflow' bugs, where the code tries to fit a gallon of information into a pint pot.

like image 155
Jonathan Leffler Avatar answered Mar 01 '26 17:03

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!