How to find the length of unsigned char* in C

2019-03-29 11:02发布

I have a variable

unsigned char* data = MyFunction();

how to find the length of data?

标签: c char
7条回答
做自己的国王
2楼-- · 2019-03-29 11:40
#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;
}

HTH

查看更多
我想做一个坏孩纸
3楼-- · 2019-03-29 11:41

There is no way to find the size of (unsigned char *) if it is not null terminated.

查看更多
我命由我不由天
4楼-- · 2019-03-29 11:52

Assuming its a string

length = strlen( char* );

but it doesn't seem to be...so there isn't a way without having the function return the length.

查看更多
三岁会撩人
5楼-- · 2019-03-29 11:53

You will have to pass the length of the data back from MyFunction. Also, make sure you know who allocates the memory and who has to deallocate it. There are various patterns for this. Quite often I have seen:

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

You then allocate data and pass datalen in. The result (int) should then indicate if your buffer (data) was long enough...

查看更多
Melony?
6楼-- · 2019-03-29 11:55

Now this is really not that hard. You got a pointer to the first character to the string. You need to increment this pointer until you reach a character with null value. You then substract the final pointer from the original pointer and voila you have the string length.

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's value is zero,
    *e.g. while(*s!=0) or just simply while(*s) */
   /* Return the difference of the incremented pointer and the original pointer */
}
查看更多
Rolldiameter
7楼-- · 2019-03-29 11:58

As said before strlen only works in strings NULL-terminated so the first 0 ('\0' character) will mark the end of the string. You are better of doing someting like this:

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

or

unsigned char* data;
unsigned int size = MyFunction(data);
查看更多
登录 后发表回答