Convert char pointer to unsigned char array

c

Solution

you cast to `unsigned char` not `unsigned char*` you forgot the `*`

part1 = (unsigned char*) pch2;

if `pch2` is not null terminated the program will crash, if you're lucky, when you use `strlen`, so you need to null terminate it first before printing using `pch2`, try this instead:

pch2[size-1] = '\0';  /* note single quote */
result.part1 = (unsigned char *) pch2;

Update: define your structure like so:

typedef struct
{
    const char *part1;
    const char *part2
    const char *part3;
    const char *part4;
} res;

And assign to it without casting at all:

result.part1 = pch2;

Problem

I want to convert a char pointer to a unsigned char var, I thought I could do that with just casting but it doesn't work: ``` char * pch2; //Code that puts something in pc2 part1 = (unsigned char) pch2; ``` I've the code to this: ``` result.part1 = (unsigned char *) pch2; printf("STRUCT %s\n",result.part1); ``` result is just a struct with unsigned char arrays. EDIT: ``` pch2 = strtok( ip, "." ); while( pch2 != NULL ){ printf( "x %d x: %s\n", i, pch2 ); pch2[size-1] = '\0'; if(i == 1) result.part1 = (unsigned char *) pch2; if(i == 2) result.part2 = (unsigned char *) pch2; if(i == 3) result.part3 = (unsigned char *) pch2; if(i == 4) result.part4 = (unsigned char *) pch2; i++; pch2 = strtok (NULL,"."); } printf("STRUCT %c\n",result.part1); ``` Struct: ``` typedef struct { unsigned char part1; unsigned char part2; unsigned char part3; unsigned char part4; } res; ```

Original source