0

I have some code that I'm trying to understand. Is it possible to get 2,3,4 back after it's stored in long int bb?

When I print out bb, I get 772. Is this a pointer value?

struct char_struct
{
   unsigned char x;
   unsigned char y;
   unsigned char z;

};
union longest
{
   unsigned long int aa;
   struct char_struct b;
};

int main()
{
   unsigned long int bb = 0;
   union longest Longest;
   Longest.b.x = 2;
   Longest.b.y = 3;
   Longest.b.x = 4;
   bb = Longest.aa;
   printf("%ld",bb);
   return 0;
 }
Kevin
  • 667
  • 2
  • 7
  • 18
  • Unions are a "one of the properties" not "all of the properties" (a struct). Do you mean to use a struct here (i.e. do you want to populate all properties at once or just one of them)? As it stands, `Longest.aa` is uninitialized when you assign it to `bb`. – ggorlen Jun 12 '19 at 00:17
  • yes all of them. – Kevin Jun 12 '19 at 00:20

1 Answers1

1

Unions in C are offer a choice of multiple members, each of which is mapped to the same memory location. If you set more than one, you're corrupting the memory of the other members.

Beyond this, Longest.aa is uninitialized, so you're printing a garbage value.

It sounds like you'd like a struct, which offers a "vertical" collection of members that can all be set and accessed simultaneously (as you're doing with char_struct). The size of the struct is at least the sum of all of its member sizes plus any cache size alignment the compiler adds.

Here's a sample program illustrating a few of these points:

#include <stdio.h>

struct char_struct {
    unsigned char x;
    unsigned char y;
    unsigned char z;
};

struct longest_t {
    unsigned long int aa;
    struct char_struct b;
};

int main() {
    unsigned long int bb = 0;
    struct longest_t longest;
    longest.b.x = 2;
    longest.b.y = 3;
    longest.b.z = 4;
    longest.aa = 42;
    bb = longest.aa;
    printf("%ld\n", bb);
    printf("%d %d %d\n", longest.b.x, longest.b.y, longest.b.z);
    printf("longest_t size: %lu\n", sizeof(struct longest_t));
    printf("char_struct size: %lu\n", sizeof(struct char_struct));
    printf("ul int size: %lu\n", sizeof(unsigned long int));
    return 0;
}

A run on my machine shows:

42
2 3 4
longest_t size: 16
char_struct size: 3
ul int size: 8

You may wish to typedef your structs, and I suggest more semantically-meaningful variable names, although I do realize this is an example program. There are a few conventions for struct names, but typically variable names are not upper camel cased like Longest.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • Thanks, it was used in someone's program. I still don't understand why it was coded that way. – Kevin Jun 12 '19 at 00:50