Casting

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
rafi

Casting

Post by rafi »

Is it possible to cast unsigned character to structure?
examble
unsigned char *c="0x1000"
structure a{int a,char c)*b;
b=(char *)c;
Is this work?If it works what will be the values a and c.
Anton

RE:Casting

Post by Anton »

The way you wrote it, it will not work, since b is of type struct a*, and the type of right side is char*. But you can try this:

typedef struct {
char a;
char c;
}a;

a *b;
unsigned int c=0x1000;
b=(a*)c;

b->a == 0;
b->c == 1;
common

RE:Casting

Post by common »

Well, structure a{int a,char c)*b; isn't valid C...so, no.
struct a {int a;char c;}*b; is though.

b = (char *)c?  You're casting from unsigned char to char, when b is of type struct a *.  b = (struct a *)c; instead.

What would be the values?  Well, that depends on what your compiler thinks.  In doing this, you'd be making the structure point to the string literal.  Based on the alignment of your structure, this may go into different locations.  If you do a sizeof(a), the size will probably be 8 or greater if you're under a 32-bit environment (PC). Of course, even though the sizeof would be 8, only 5 would be used.  How these are used are platform dependent, and may have a direct relationship to multibyte characters (little/big endian formats).

If you're doing this, you might be trying to get the structure to point to a specific memory location?  Well you can do that by just:

   b = ((struct a *)0x1000);

If you have a value in 'c' that you want converted, use something like strtoul.

  unsigned long int v;
  v = strtoul(c, NULL, 16);
  b = ((struct a *)v);
  b->a = 5; ...

Of course, that's assuming that a sizeof(unsigned long int) = sizeof(struct a *) on your system.
Post Reply