union.c

/*
 * demonstrate how a union works
 *
 * this sets up something as a string and then
 * accesses it as an integer
 *
 * Matt Bishop, ECS 36A, Fall 2019
 */
#include <stdio.h>
#include <string.h>

/*
 * union to treat a variable
 * as either an integer or an
 * array of characters
 */
union chtoint {
	int x;			/* ... as an integer */
	char a[8];		/* ... as 7 characters (+ '\0') */
};

/*
 * the string to use
 * the characters are (in hex):
 * 30, 31, 32, 33, 34, 35, 36, 37, 0
 */
char *str = "1234567";

/*
 * and now the conversion
 */
int main(void)
{
	union chtoint u;	/* u can be treated as an integer or a string */

	/*
	 * give u a string value
	 * note overflow won't occur here
	 */
	strcpy(u.a, str);
	
	/*
	 * now print it out as a string, a hexadecimal integer,
	 * and a decimal integer
	 */
	printf("%s -- 0x%x or %d\n", u.a, u.x, u.x);

	/* bye! */
	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh