top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C: Changing value in Union resulting in error?

+2 votes
244 views
typedef union
{
    int integer;
    char* string;
} Value;

main()
{
  Value v = { 1 };
  v = { 2 }; // getting the error on this 
}
posted May 2, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes

Curly braces used at the time of initialization only. Once the initialized section got over, union or structure variables members are accessed by using "dot" operator.

answer May 3, 2015 by Vikram Singh
0 votes

You should access a union member using a dot operator. Eg. - v.integer=0; v.string=NULL;

This works fine in the first line because it is an initialization.

Value v= { 1 } ;

Infact it is called partial initialization where if you initialize just one or more members, the rest are treated to be assigned as 0. Curly braces work only in case of initialization.

answer May 4, 2015 by Ankush Surelia
Similar Questions
+4 votes

case:1

int main(void)
{
  extern int var = 0;
  var = 10;
  return 0;
}

case:2

#include<stdio.h>
extern int a;
int main()
{
 extern int a;
 int a=34;
 printf("%d",a);
 return 0;
}

In both cases it's error why so? Curious to know exactly how declaration of variable with extern differ locally and globally ?

More informative answer is most welcome.

+2 votes
+2 votes

See the following program, sizeof is resulting different output for the different function. Can someone explain this/

#include<stdio.h>

void main()
{
    int arr[]={1,2,3,4,5};
    printf("length: %d\n",sizeof(arr));
    printf("length: %d\n",sizeof(arr)/sizeof(int));
    show(arr);
}

void show(int ar[])
{
   printf("length: %d\n", sizeof(ar));
   printf("length: %d\n", sizeof(ar)/sizeof(int));
}

Output

length: 20
length: 5
length: 4
length: 1
...