Hi all - apologies if this is a tired old question. I couldn't find anything on first glance in the forums or tutorials.
I'm new to C, and I'm trying to find out from inside a function how many characters have been allocated in memory to a string array. The catch is that the function only has a pointer to the array that it takes as an argument. I've tried something like this:
(Obviously there would be no point in the get_free_chars function alone - I'm trying to do something similar within a string manipulation function I'm coding)Code:#include <stdlib.h> int get_free_chars(char *ptr) { return sizeof(ptr)/sizeof(char); } main() { char foo[50] = ""; int a = sizeof(foo) / sizeof(char); int b = get_free_chars(foo); }
'a' takes the value I'd expect - 50 - but 'b' comes out to be 4 (obviously because the program is measuring the size of the pointer (4 bytes = 32 bits, which is the size for my system) rather than the array itself). Doing sizeof(*ptr) obviously wouldn't work as that would point directly to the first character only.
Is there a nice way to get this information from within the function?
Thanks in advance!