Originally Posted by
sockets12
Hello,I want to count the number of bytes in a stream that contains nulls. I know I can't use strlen() for this, so is there an alternative?
Code:
char *bytes = "\x11\x12\x13\x00\x12\x13\x14\x15";
I want to be able to say there's 8 bytes here, not 3 as strlen gives me.Thank you!
Then you will have to track the size separately. You have two options. The first is to make bytes a char array
Code:
unsigned char bytes[] = {0x11, 0x12, 0x13, 0x00, 0x12, 0x13, 0x14, 0x15};
sizeof(bytes);
That has the disadvantage that, when passed to a function, bytes becomes a simple unsigned char *, so you can't use sizeof on it anymore, you have to pass in the size as another parameter to the function. But it has the advantage that you don't waste 4 (or 8 or whatever) bytes on a len member all the time. So long as you can use sizeof, which is computed at compile time, you save space.
The second is to make a struct that has a length member
Code:
struct byte_array {
unsigned char *data;
size_t len;
};
struct byte_array bytes = {"\x11\x12\x13\x00\x12\x13\x14\x15", 8};
bytes.data;
bytes.len;
Upside, you always have the length available. Downside, it takes up extra space. Another downside is that, if you make data point to a string literal (a.k.a. a string constant), then you can't modify the data (it's constant). You need to point it to modifiable data (e.g. an array) or malloc memory and copy the contents -- just remember to free it.
That's it. Arrays in C don't actually carry their length with them, nor do pointers contain any info about the memory pointed to, other than the starting address. It's your job to track that if you care. Furthermore, the C string functions definitely wont work. By definition, a string in C is a sequence of contiguous bytes ending in a byte with a zero value (a null byte). Thus things like strlen, strcpy, etc will definitely break.