Skip to main content
parisa
Associate III
September 11, 2016
Question

Union in C language problem

  • September 11, 2016
  • 2 replies
  • 653 views
Posted on September 11, 2016 at 13:50

Hello

I have written a code like this:

#include <
stdio.h
>
#include <
string.h
>
#include ''stm32f10x_gpio.h''
#include ''stm32f10x_rcc.h''
#include ''stm32f10x_usart.h''
#include ''stm32f10x_dma.h''
union receive{
unsigned long int Pack;
};
union receive var1; 
void check(char data1,char data2){
unsigned long int buffer[17];
buffer[0]=123456;
var1.Pack=buffer[0];
printf(''innn%ld'',var1.Pack);
}

but it returns 1 instead of 123456 or when I fill it with 654321 value it returns again 1. what is my mistake?
    This topic has been closed for replies.

    2 replies

    Tesla DeLorean
    Guru
    September 11, 2016
    Posted on September 11, 2016 at 22:49

    This lacks sufficient context to know why exactly it is failing.

    I'd suspect it is an issue with the the C startup code initializing things, or the code generation. I would suggest you look at the generated code, and step through the assembler instructions in the debugger to get a better grasp about why it isn't working correctly.

    Tips, Buy me a coffee, or three.. PayPal VenmoUp vote any posts that you find helpful, it shows what's working..
    AvaTar
    Senior III
    September 12, 2016
    Posted on September 12, 2016 at 08:12

    From the provided example, I fail to grasp the reasoning for using a union.

    You could have used a struct, or even a simple integer as well ...