C Exercises: Show a pointer to union
C Pointer : Exercise-19 with Solution
Write a program in C to show a pointer to a union.
Visual Presentation:
Sample Solution:
C Code:
#include <stdio.h>
// Defining a union to hold employee address details
union empAdd {
char *ename; // Employee name (string pointer)
char stname[20]; // Street name (array of characters)
int pincode; // Pincode (integer)
};
// Main function
int main() {
// Displaying the purpose of the program
printf("\n\n Pointer : Show a pointer to union :\n");
printf("----------------------------------------\n");
union empAdd employee, *pt; // Declaring union variables
// Assigning a string up to the null character ('\0') to the union member
employee.ename = "John Mc\0Donald"; // Assigning the string up to null character
pt = &employee; // Storing the address of the union variable in a pointer
// Printing the content of the union member using pointer to union
printf(" %s %s\n\n", pt->ename, (*pt).ename);
return 0;
}
Sample Output:
Pointer : Show a pointer to union : ---------------------------------------- Jhon Mc Jhon Mc
Flowchart:
C Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a program in C to show the usage of pointer to structure.
Next: Write a program in C to show a pointer to an array which contents are pointer to structure.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming-exercises/pointer/c-pointer-exercise-19.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics