0% found this document useful (0 votes)
16 views

Pointer, Structure and Union

Uploaded by

shipluislam24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Pointer, Structure and Union

Uploaded by

shipluislam24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

C Pointers

A pointer is a variable that stores the memory address of another


variable as its value.
A pointer variable points to a data type (like int) of the same type, and
is created with the * operator. The address of the variable you are
working with is assigned to the pointer:
Example
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that stores
the address of myAge

// Output the value of myAge (43)


printf("%d\n", myAge);

// Output the memory address of myAge (0x7ffe5367e044)


printf("%p\n", &myAge);

// Output the memory address of myAge with the pointer


(0x7ffe5367e044)
printf("%p\n", ptr);

Example explained
Create a pointer variable with the name ptr, that points to an int variable
(myAge). Note that the type of the pointer has to match the type of the
variable you're working with (int in our example).
Use the & operator to store the memory address of the myAge variable,
and assign it to the pointer.
Now, ptr holds the value of myAge's memory address.

In the example above, we used the pointer variable to get the memory
address of a variable (used together with the & reference operator).
You can also get the value of the variable the pointer points to, by using
the * operator (the dereference operator):
Example
int myAge = 43; // Variable declaration
int* ptr = &myAge; // Pointer declaration

// Reference: Output the memory address of myAge with the pointer


(0x7ffe5367e044)
printf("%p\n", ptr);

// Dereference: Output the value of myAge with the pointer (43)


printf("%d\n", *ptr);

Note that the * sign can be confusing here, as it does two different things
in our code:
• When used in declaration (int* ptr), it creates a pointer variable.
• When not used in declaration, it act as a dereference operator.

Good To Know: There are two ways to declare pointer variables in C:


int* myNum;
int *myNum;
// C Program to Swap Two Numbers using Pointers
#include <stdio.h>
void swap_numbers(int *ptr1, int *ptr2) {
int temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}

void main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
swap_numbers(&num1, &num2);
printf("The swapped numbers are: %d %d", num1, num2);
}
C Pointers and Arrays
Pointers & Arrays
You can also use pointers to access arrays. Consider the following array
of integers:
Example
int myNumbers[4] = {25, 50, 75, 100};

Example
int myNumbers[4] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {


printf("%d\n", myNumbers[i]);
}
Result:
25
50
75
100
Instead of printing the value of each array element, let's print the
memory address of each array element:
Example
int myNumbers[4] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {


printf("%p\n", &myNumbers[i]);
}

Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f4
0x7ffe70f9d8f8
0x7ffe70f9d8fc
C Structures (structs)
Structures (also called structs) are a way to group several related
variables into one place. Each variable in the structure is known as
a member of the structure.
Unlike an array, a structure can contain many different data types (int,
float, char, etc.)
Create a Structure
You can create a structure by using the struct keyword and declare each
of its members inside curly braces:
struct MyStructure { // Structure declaration
int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon
To access the structure, you must create a variable of it.
Use the struct keyword inside the main() method, followed by the name
of the structure and then the name of the structure variable:
Create a struct variable with the name "s1":
struct myStructure {
int myNum;
char myLetter;
};

int main() {
struct myStructure s1;
return 0;
}
Access Structure Members
To access members of a structure, use the dot syntax (.):
Example
// Create a structure called myStructure
struct myStructure {
int myNum;
char myLetter;
};

int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;

// Assign values to members of s1


s1.myNum = 13;
s1.myLetter = 'B';

// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);

return 0;
}
Now you can easily create multiple structure variables with different
values, using just one structure:
Example
// Create different struct variables
struct myStructure s1;
struct myStructure s2;

// Assign values to different struct variables


s1.myNum = 13;
s1.myLetter = 'B';

s2.myNum = 20;
s2.myLetter = 'C';

Simpler Syntax
You can also assign values to members of a structure variable at declaration
time, in a single line.

Example
// Create a structure
struct myStructure {
int myNum;
char myLetter;
char myString[30];
};

int main() {
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};
// Print values
printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);

return 0;
}

C Unions
The Union is a user-defined data type in C language that can contain
elements of the different data types just like structure. But unlike
structures, all the members in the C union are stored in the same
memory location. Due to this, only one member can store data at the
given instance.
Syntax of Union in C
The syntax of the union in C can be divided into three steps which are as
follows:
C Union Declaration
In this part, we only declare the template of the union, i.e., we only
declare the members’ names and data types along with the name of the
union. No memory is allocated to the union in the declaration.
union union_name {
datatype member1;
datatype member2;
...
};

Keep in mind that we have to always end the union declaration with a
semi-colon.

Different Ways to Define a Union Variable


We need to define a variable of the union type to start using union
members. There are two methods using which we can define a union
variable.
1. With Union Declaration
2. After Union Declaration
1. Defining Union Variable with Declaration
union union_name {
datatype member1;
datatype member2;
...
} var1, var2, ...;
2. Defining Union Variable after Declaration
union union_name var1, var2, var3...;
where union_name is the name of an already declared union.
Access Union Members
We can access the members of a union by using the ( . ) dot operator just
like structures.
var1.member1;
where var1 is the union variable and member1 is the member of the
union.The above method of accessing the members of the union also
works for the nested unions.
var1.member1.memberA;
Here,
• var1 is a union variable.
• member1 is a member of the union.
• memberA is a member of member1.

Initialization of Union in C
The initialization of a union is the initialization of its members by
simply assigning the value to it.
var1.member1 = some_value;
One important thing to note here is that only one member can contain
some value at a given instance of time.
Example of Union
#include <stdio.h>
union un {
int member1;
char member2;
float member3;
};
int main(){
// defining a union variable
union un var1;
// initializing the union member
var1.member1 = 15;
printf("The value stored in member1 = %d",var1.member1);
return 0;
}

Output: The value stored in member1 = 15

Size of Union
The size of the union will always be equal to the size of the largest
member of the array. All the less-sized elements can store the data in the
same space without any overflow.
Memory Allocation in C Union
Difference between C Structure and C Union
The following table lists the key difference between the structure and
union in C:

Structure Union

The size of the structure is equal to or greater The size of the union is the size
than the total size of all of its members. of its largest member.

The structure can contain data in multiple Only one member can contain
members at the same time. data at the same time.

It is declared using the union


It is declared using the struct keyword.
keyword.

###Example:

#include <stdio.h>

union unionJob

{
//defining a union

char name[32];

float salary;

int workerNo;

} uJob;

struct structJob

char name[32];

float salary;

int workerNo;

} sJob;

int main(){

printf("size of union = %d bytes", sizeof(uJob));

printf("\nsize of structure = %d bytes", sizeof(sJob));

return 0;

Output

size of union = 32

size of structure = 40

Why this difference in the size of union and structure variables?


Here, the size of sJob is 40 bytes because

• the size of name[32] is 32 bytes

• the size of salary is 4 bytes

• the size of workerNo is 4 bytes

However, the size of uJob is 32 bytes. It's because the size of a union variable will
always be the size of its largest element. In the above example, the size of its
largest element, (name[32]), is 32 bytes.

With a union, all members share the same memory.

You might also like