Possible Duplicate:
C -> sizeof string is always 8
I found the following way to create a string:
#include <stdio.h>
#include <string.h>
int main(void) {
char *ptr = "this is a short string";
int count = sizeof ptr / sizeof ptr[0];
int count2 = strlen(ptr);
printf("the size of array is %d\n", count);
printf("the size of array is %d\n", count2);
return 0;
}
I can’t use the the usual way to get the length by sizeof ptr / sizeof ptr[0], Does this way to create string is valid? Any pros and cons about his notation?
Because
ptris a pointer and not an array. If you usedchar ptr[]instead ofchar *ptr, you would have gotten an almost-correct result – instead of 22, it would have resulted in 23, since the size of the array incorporates the terminatingNULbyte also, which is not counted bystrlen().By the way, “creating” a string like this is (almost) valid, but if you don’t use a character array, the compiler will initialize the pointer with the address of an array of constant strings, so you should really write
instead of what you have now (i. e. add the
constqualifier).