How to find unsigned char * length in C

I have a variable

unsigned char* data = MyFunction(); 

How to find the length of the data?

+6
c char
source share
7 answers

You will need to pass the data length from MyFunction . Also, make sure you know who allocates memory and who frees it. There are various templates for this. Quite often I saw:

 int MyFunction(unsigned char* data, size_t* datalen) 

Then you select the data and pass the datalen. The result (int) should then indicate if your buffer (data) was long enough ...

+9
source share

Assuming a string

 length = strlen( char* ); 

but it doesn't seem to be so ... so there is no way for the function to not return the length.

+6
source share

Unable to find size ( unsigned char *) if it is not terminated by zero.

+3
source share

Now it really is not that difficult. You have a pointer to the first character of the string. You need to increase this pointer until you reach the character with a null value. Then you extract the final pointer from the original pointer and voila, you have the length of the string.

 int strlen(unsigned char *string_start) { /* Initialize a unsigned char pointer here */ /* A loop that starts at string_start and * is increment by one until it value is zero, *eg while(*s!=0) or just simply while(*s) */ /* Return the difference of the incremented pointer and the original pointer */ } 
+2
source share

As already mentioned, strlen only works on lines ending in NULL, so the first character 0 ('\ 0') marks the end of the line. You better do the following:

 unsigned int size; unsigned char* data = MyFunction(&size); 

or

 unsigned char* data; unsigned int size = MyFunction(data); 
+1
source share

The original question did not say that the returned data is a zero-terminated string. If not, there is no way to find out how big the data is. If it's a string, use strlen or write your own. The only reason not to use strlen is the homework problem, so I'm not going to describe it for you.

+1
source share
 #include <stdio.h> #include <limits.h> int lengthOfU(unsigned char * str) { int i = 0; while(*(str++)){ i++; if(i == INT_MAX) return -1; } return i; } 

NTN

-5
source share

All Articles