If I have a character pointer that contains NULL bytes is there any built in function I can use to find the length or will I just have to write my own function? Btw I’m using gcc.
EDIT:
Should have mentioned the character pointer was created using malloc().
If you have a pointer then the ONLY way to know the size is to store the size separately or have a unique value which terminates the string. (typically
'\0') If you have neither of these, it simply cannot be done.EDIT: since you have specified that you allocated the buffer using
mallocthen the answer is the paragraph above. You need to either remember how much you allocated withmallocor simply have a terminating value.If you happen to have an array (like:
char s[] = "hello\0world";) then you could resort tosizeof(s). But be very careful, the moment you try it with a pointer, you will get the size of the pointer, not the size of an array. (butstrlen(s)would equal5since it counts up to the first'\0').In addition, arrays decay to pointers when passed to functions. So if you pass the array to a function, you are back to square one.
NOTE:
and
and
are all the same. In all 3 versions,
pis a pointer, not an array.