C Unit 4 notes
C Unit 4 notes
1. Definition of Structure
2. Declaration of a Structure
Syntax:
struct StructureName {
dataType member1;
dataType member2;
// additional members
};
Example:
struct Person {
char name[50];
int age;
float height;
};
Here, Person is a structure with three members: name, age, and height.
Syntax:
structureVariable.memberName
Example:
struct Person p1;
strcpy(p1.name, "Alice"); // Accessing the 'name' member of 'p1'
p1.age = 25; // Accessing the 'age' member of 'p1'
p1.height = 5.6; // Accessing the 'height' member of 'p1'
For accessing structure members via pointers, you
use the arrow operator (->). Example:
struct Person *ptr = &p1;
printf("Name: %s\n", ptr->name); // Using pointer
to access structure member 4. Structure
Initialization
Structures can be initialized at the time of declaration, just like arrays.
Example:
struct Person p1 = {"Alice", 25, 5.6};
5. Structure Operations
Example:
struct Person p1 = {"Alice", 25, 5.6};
struct Person p2;
p2 = p1; // Copying all members of p1 to p2
6. Nested Structures
Example:
struct Address {
char city[50];
char state[50];
};
struct Person {
char name[50];
int age;
struct Address address; // Nested structure
};
1. Definition of Union
2. Declaration of a Union
Syntax:
union UnionName {
dataType member1;
dataType member2;
// additional members
};
Example:
union Data {
int i;
float f;
char c;
};
Union members are accessed using the dot operator (.) just like
structure members.
Example:
union Data data;
data.i = 10; // Assigning an integer to the union
printf("%d\n", data.i); // Output: 10
Example:
union Data data = {10}; // Initializes the first member, 'i', of the union
5. Size of a Union
Example:
union Data data;
printf("Size of union: %lu\n", sizeof(data)); // Output: Size of
union: 4 (assuming the largest member is an integer)