简体   繁体   中英

C Programming: Find Length of a Char* with Null Bytes

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 malloc then the answer is the paragraph above. You need to either remember how much you allocated with malloc or simply have a terminating value.

If you happen to have an array (like: char s[] = "hello\\0world"; ) then you could resort to sizeof(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. (but strlen(s) would equal 5 since 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:

void f(int *p) {}

and

void f(int p[]) {}

and

void f(int p[10]) {}

are all the same . In all 3 versions, p is a pointer , not an array.

How do you know where the string ends, if it contains NULL bytes as part of it? Certainly no built in function can work with strings like that. It'll interpret the first null byte as the end of the string.

If you want the length, you'll have to store it yourself. Keep in mind that no standard library string functions will work correctly on strings like these.

You'll need to keep track of the length yourself.

C strings are null terminated , meaning that the first null character signals the end of the string. All builtin string functions rely on this, so if you have a buffer that can contain NULLs as part of the data then you can't use them.

Since you're using malloc then you may need to keep track of two sizes: the size of your allocated buffer, and how many characters within that buffer constitute valid data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM