Home > Back-end >  typecast structure member in C during assignment
typecast structure member in C during assignment

Time:08-25

Is there a way to type cast structure member during its initiation, for instance:

struct abc {
    char k;
};
 
int main()
{
  struct abc data[] = {.k= 'TI'};
}

Above wouldn't work since k is of type char, is there way to type caste this member k (to int) during its assignment to 'TI' ?

CodePudding user response:

No matter what you do to the value, it doesn't change the fact that the field cannot store that much information. You will need to change the type of k.

CodePudding user response:

You don't need a cast here.

struct abc {
    char k;
};
 
int main()
{
  struct abc data[] = {.k= 'TI'};
}

Your object data is an array of struct abc. The initializer is fo an object of type struct abc.

If you want data to be a 1-element array, you can do this:

  struct abc data[] = {{.k= 'TI'}};

or, if you want to be more explicit:

   struct abc data[] = {[0] = {.k = 'TI'}};

That's valid code, but it's likely to trigger a warning. 'TI' is a multi-character constant, an odd feature of C that in my experience is used by accident more often than it's used deliberately. Its value is implementation-defined, and it's of type int.

Using gcc on my system, its value is 21577, or 0x5449, which happens to be ('T' << 8) 'I'. Since data[0].k is a single byte, it can't hold that value. There's an implicit conversion from int to char that determines the value that will be stored (in this case, on my system, 73, which happens to be 'I').

A cast (not a "type cast") converts a value from one type to another. It doesn't change the type of an object. k is of type char, and that's not going to change unless you modify its declaration. Maybe you want to have struct abc { int k; };?

I can't help more without knowing what you're trying to do. Why are you using a multi-character constant? Why is k of type char?

CodePudding user response:

"...I was thinking if member K which of type char can be type caste to int ..."

From the context in your post, and in comments, I am guessing you mean to say cast, not type cast (enter image description here

Note: compiled using GNU GCC, set to follow C99 rules

CodePudding user response:

  1. 'TI' is wrong you probably mean string "TI"
  2. If typecast mean see the sting "TI" as integer you need to use union - it is called type punning.
typedef union 
{
    char k[2]; //I do not want to store null terminating character
    short int x;
}union_t;

int main(void)
{
    union_t u = {.k = "TI"};

    printf("u.k[0]=%c (0x%x), u.k[1]=%c (0x%x) u.x = %hd (0x%hx)\n", u.k[0], u.k[0], u.k[1], u.k[1], u.x, u.x);
}

https://godbolt.org/z/EhbKG5qnW

  • Related