Granit
Granit

Reputation:

How to find the length of unsigned char* in C

I have a variable

unsigned char* data = MyFunction();

how to find the length of data?

Upvotes: 7

Views: 47999

Answers (7)

kenny
kenny

Reputation: 22334

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.

Upvotes: 6

mch
mch

Reputation: 31

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

Upvotes: 3

plan9assembler
plan9assembler

Reputation: 2984

#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

Upvotes: -5

Reputation:

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);

Upvotes: 1

Larry Gritz
Larry Gritz

Reputation: 13690

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

Upvotes: 1

Tamas Czinege
Tamas Czinege

Reputation: 121314

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 */
}

Upvotes: 2

Daren Thomas
Daren Thomas

Reputation: 70324

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...

Upvotes: 9

Related Questions