There are plenty of similar inquires, but in my case I don\'t understand what isn\'t working:
int mysize = 0;
mysize = sizeof(samplestring) / sizeof(*samplestrin
It looks as though you have a pointer, not an array. Arrays are converted to pointers when the program requires it, so you'd get:
size_t size(char * p) { // p is a pointer
return sizeof(p) / sizeof(*p); // size of pointer
}
size_t size(char p[]) { // p is also a pointer
return sizeof(p) / sizeof(*p); // size of pointer
}
although, since sizeof (char) == 1
, the division is redundant here; if the pointer were to a larger type, then you'd get a differently unexpected result.
In C++ (but obviously not C), you can deduce the size of an array as a template parameter:
template
size_t size(T (&)[N]) {
return N; // size of array
}
or you can use classes such as std::vector
and std::string
to keep track of the size.
In C, you can use strlen
to find the length of a zero-terminated string, but in most cases you'll need to keep track of array sizes yourself.