TurtleFan
TurtleFan

Reputation: 289

Converting between two types in c

I have data of type char data[500]; which I need to put into a function which takes unsigned char* data. How can I convert between the two? I'm a c noob.

Upvotes: 0

Views: 541

Answers (3)

Idos
Idos

Reputation: 15310

Take a try at this:

unsigned char* des;
des = malloc(500 * sizeof(unsigned char));
strncpy(des, data, 500);

Then you should be able to call:

func(des);

Upvotes: 0

Sudipta Kumar Sahoo
Sudipta Kumar Sahoo

Reputation: 1147

You can Simply type cast to unsigned char Here is an example

void method(unsigned char *data)
{
    printf("%c",*(data+5));
}
int main()
{
  char arr[10];
  arr[5] = 's';
  method((unsigned char*)arr);
}

Hope This Helps.

Upvotes: 3

R Sahu
R Sahu

Reputation: 206577

One of the following should work.

  1. Cast the data before calling the function.

    char data[500];
    function((unsigned char*)data);
    
  2. Copy the data before calling the function.

    unsigned char copyOfData[500];
    memcpy(copyOfData, data, 500);
    function(copyOfData);
    
  3. Start with unsigned char data type.

    unsigned char data[500];
    function(data);
    

Upvotes: 2

Related Questions