Vous êtes sur la page 1sur 25

UNIT -6

What is Structure
Structure in c is a user-defined data type that enables us to store the collection of different
data types. Each element of a structure is called a member. Structures ca; simulate the use of
classes and templates as it can store various information

The ,struct keyword is used to define the structure. Let's see the syntax to define the structure
in c.

1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };

Let's see the example to define a structure for an entity employee in c.

1. struct employee
2. { int id;
3. char name[20];
4. float salary;
5. };

The following image shows the memory allocation of the structure employee that is defined
in the above example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are
the members or fields of the structure. Let's understand it by the diagram given below:

Declaring structure variable


We can declare a variable for the structure so that we can access the member of the structure
easily. There are two ways to declare structure variable:

1. By struct keyword within main() function


2. By declaring a variable at the time of defining the structure.

1st way:

Let's see the example to declare the structure variable by struct keyword. It should be
declared within the main function.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };

Now write given code inside the main() function.

1. struct employee e1, e2;

The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and
e2 can be treated in the same way as the objects in C++ and Java.

2nd way:

Let's see another way to declare variable at the time of defining the structure.

1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. }e1,e2;

Which approach is good

If number of variables are not fixed, use the 1st approach. It provides you the flexibility to
declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in
main() function.

Accessing members of the structure


There are two ways to access structure members:

1. By . (member or dot operator)


2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

1. p1.id

C Structure example
Let's see a simple example of structure in C language.
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for structure
7. int main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }

Output:

employee 1 id : 101
employee 1 name : Sonoo Jaiswal

C Union
Like structure, Union in c language is a user-defined data type that is used to store the
different type of elements.

At once, only one member of the union can occupy the memory. In other words, we can say
that the size of the union in any instance is equal to the size of its largest element.

Advantage of union over structure

It occupies less memory because it occupies the size of the largest member only.
Disadvantage of union over structure

Only the last entered data can be stored in the union. It overwrites the data previously stored
in the union.

Defining union
The union keyword is used to define the union. Let's see the syntax to define union in c.

1. union union_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };

Let's see the example to define union for an employee in c.

1. union employee
2. { int id;
3. char name[50];
4. float salary;
5. };

C Union example

Let's see a simple example of union in C language.

1. #include <stdio.h>
2. #include <string.h>
3. union employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for union
7. int main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }
Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

Difference Between Structure and Union


May 9, 2016 4 Comments

C++ allows all the five ways that the C


language provided to create a custom data. Those five ways are ‘structure’, ‘bit-field’,
‘union’, ‘enumeration’, ‘typedef’. In the article below we are going to study the difference
between structure and union. The structure and union both are the container data types that
can hold data of any “type”. The one major difference that distinguishes structure and union
is that the structure has a separate memory location for each of its members whereas, the
members of a union share the same memory location.

Let’s understand the difference between structure and union, along with a comparison chart.

Structure Vs Union
Comparison Chart
Basis of
Structure Union
Comparison

The separate memory location is All members of the 'union'


Basic allotted to each member of the share the same memory
'structure'. location.

struct struct_name{ union u_name{


type element1; type element1;
type element2; type element2;
Declaration
. .
. .
} variable1, variable2, ...; } variable1, variable2, ...;
Basis of
Structure Union
Comparison

keyword 'struct' 'union'

Size of Structure= sum of size of all Size of Union=size of the


Size
the data members. largest members.

Stores distinct values for all the Stores same value for all
Store Value
members. the members.

A 'structure' stores multiple A 'union' stores a single


At a Time values, of the different members, value at a time for all
of the 'structure'. members.

Provide multiple way to to


Way of Provide single way to view each
view same memory
Viewing memory location.
location.

Anonymous Anonymous union can be


No Anonymous feature.
feature declared.

Pointers in C Programming with examples


A pointer is a variable that stores the address of another variable. Unlike other variables that hold
values of a certain type, pointer holds the address of a variable. For example, an integer variable
holds (or you can say stores) an integer value, however an integer pointer holds the address of a
integer variable.
#include <stdio.h>
int main()
{
int num = 10;
printf("Value of variable num is: %d", num);
/* To print the address of a variable we use %p
* format specifier and ampersand (&) sign just
* before the variable name like &num.
*/
printf("\nAddress of variable num is: %p", &num);
return 0;
}

Output:

Value of variable num is: 10


Address of variable num is: 0x7fff5694dc58
A Simple Example of Pointers in C
#include <stdio.h>
int main()
{
//Variable declaration
int num = 10;

//Pointer declaration
int *p;

//Assigning address of num to the pointer p


p = #

printf("Address of variable num is: %p", p);


return 0;
}

Output:

Address of variable num is: 0x7fff5694dc58


“Address of”(&) Operator

We have already seen in the first example that we can display the address of a variable using
ampersand sign. I have used &num to access the address of variable num. The & operator is
also known as “Address of” Operator.

printf("Address of var is: %p", &num);

Point to note: %p is a format specifier which is used for displaying the address in hex
format.
Now that you know how to get the address of a variable but how to store that address in
some other variable? That’s where pointers comes into picture. As mentioned in the
beginning of this guide, pointers in C programming are used for holding the address of
another variables.

Pointer is just like another variable, the main difference is that it stores address of
another variable rather than a value.

“Value at Address”(*) Operator


The * Operator is also known as Value at address operator.
How to declare a pointer?

int *p1 /*Pointer to an integer variable*/


double *p2 /*Pointer to a variable of data type double*/
char *p3 /*Pointer to a character variable*/
float *p4 /*pointer to a float variable*/
Example of Pointer demonstrating the use of & and *
#include <stdio.h>
int main()
{
/* Pointer of integer type, this can hold the
* address of a integer type variable.
*/
int *p;

int var = 10;

/* Assigning the address of variable var to the pointer


* p. The p can hold the address of var because var is
* an integer type variable.
*/
p= &var;

printf("Value of variable var is: %d", var);


printf("\nValue of variable var is: %d", *p);
printf("\nAddress of variable var is: %p", &var);
printf("\nAddress of variable var is: %p", p);
printf("\nAddress of pointer p is: %p", &p);
return 0;
}

Output:

Value of variable var is: 10


Value of variable var is: 10
Address of variable var is: 0x7fff5ed98c4c
Address of variable var is: 0x7fff5ed98c4c
Address of pointer p is: 0x7fff5ed98c50
C - Pointer to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains
the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, the following declaration declares a
pointer to a pointer of type int −

int **var;

When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example −

Live Demo
#include <stdio.h>

int main () {

int var;
int *ptr;
int **pptr;

var = 3000;

/* take the address of var */


ptr = &var;

/* take the address of ptr using address of operator & */


pptr = &ptr;

/* take the value using pptr */


printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);

return 0;
}

When the above code is compiled and executed, it produces the following result −

Value of var = 3000


Value available at *ptr = 3000
Value available at **pptr = 3000
Dynamic Memory Allocation in C using malloc(), calloc(), free() and
realloc()
Since C is a structured language, it has some fixed rules for programming. One of it includes
changing the size of an array. An array is collection of items stored at continuous memory
locations.

As it can be seen that the length (size) of the array above made is 9. But what if there is a
requirement to change this length (size). For Example,

 If there is a situation where only 5 elements are needed to be entered in this array. In this
case, the remaining 4 indices are just wasting memory in this array. So there is a
requirement to lessen the length (size) of the array from 9 to 5.

 Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But
there is a need to enter 3 more elements in this array. In this case 3 indices more are
required. So the length (size) of the array needs to be changed from 9 to 12.

This procedure is referred to as Dynamic Memory Allocation in C.

Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size
of a data structure (like Array) is changed during the runtime.

C provides some functions to achieve these tasks. There are 4 library functions provided by C
defined under <stdlib.h> header file to facilitate dynamic memory allocation in C
programming. They are:

1. malloc()
2. calloc()
3. free()
4. realloc()

Let’s look at each of them in greater detail.

1. C malloc() method
“malloc” or “memory allocation” method in C is used to dynamically allocate a
single large block of memory with the specified size. It returns a pointer of type void
which can be cast into a pointer of any form.

Syntax:

ptr = (cast-type*) malloc(byte-size)

For Example:

ptr = (int*) malloc(100 * sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And,
the pointer ptr holds the address of the first byte in the allocated memory.

If space is insufficient, allocation fails and returns a NULL pointer.

Example:

filter_none

edit

play_arrow

brightness_4

#include <stdio.h>

#include <stdlib.h>
int main()

// This pointer will hold the

// base address of the block created

int* ptr;

int n, i, sum = 0;

// Get the number of elements for the array

n = 5;

printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()

ptr = (int*)malloc(n * sizeof(int));

// Check if the memory has been successfully

// allocated by malloc or not

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {

// Memory has been successfully allocated

printf("Memory successfully allocated using malloc.\n");

// Get the elements of the array

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

ptr[i] = i + 1;

// Print the elements of the array

printf("The elements of the array are: ");


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

printf("%d, ", ptr[i]);

return 0;

Output:

Enter number of elements: 5


Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,

2. C calloc() method

“calloc” or “contiguous allocation” method in C is used to dynamically allocate the


specified number of blocks of memory of the specified type. It initializes each block
with a default value ‘0’.

Syntax:

ptr = (cast-type*)calloc(n, element-size);

For Example:

ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for 25 elements each with the
size of the float.
If space is insufficient, allocation fails and returns a NULL pointer.

Example:

filter_none

edit

play_arrow

brightness_4

#include <stdio.h>

#include <stdlib.h>

int main()

// This pointer will hold the

// base address of the block created

int* ptr;

int n, i, sum = 0;

// Get the number of elements for the array

n = 5;

printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()

ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully

// allocated by malloc or not

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

}
else {

// Memory has been successfully allocated

printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array

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

ptr[i] = i + 1;

// Print the elements of the array

printf("The elements of the array are: ");

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

printf("%d, ", ptr[i]);

return 0;

Output:

Enter number of elements: 5


Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,

3. C free() method

“free” method in C is used to dynamically de-allocate the memory. The memory


allocated using functions malloc() and calloc() is not de-allocated on their own. Hence
the free() method is used, whenever the dynamic memory allocation takes place. It
helps to reduce wastage of memory by freeing it.

Syntax:

free(ptr);
Example:

#include <stdio.h>

#include <stdlib.h>

int main()

// This pointer will hold the

// base address of the block created

int *ptr, *ptr1;

int n, i, sum = 0;

// Get the number of elements for the array

n = 5;

printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()

ptr = (int*)malloc(n * sizeof(int));

// Dynamically allocate memory using calloc()


ptr1 = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully

// allocated by malloc or not

if (ptr == NULL || ptr1 == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {

// Memory has been successfully allocated

printf("Memory successfully allocated using malloc.\n");

// Free the memory

free(ptr);

printf("Malloc Memory successfully freed.\n");

// Memory has been successfully allocated

printf("\nMemory successfully allocated using calloc.\n");

// Free the memory

free(ptr1);

printf("Calloc Memory successfully freed.\n");

return 0;

Output:

Enter number of elements: 5


Memory successfully allocated using malloc.
Malloc Memory successfully freed.

Memory successfully allocated using calloc.


Calloc Memory successfully freed.
4. C realloc() method

“realloc” or “re-allocation” method in C is used to dynamically change the memory


allocation of a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is insufficient, realloc can be used to
dynamically re-allocate memory.

Syntax:

ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize'.

If space is insufficient, allocation fails and returns a NULL pointer.

#include <stdio.h>

#include <stdlib.h>

int main()

// This pointer will hold the

// base address of the block created

int* ptr;

int n, i, sum = 0;
// Get the number of elements for the array

n = 5;

printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()

ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully

// allocated by malloc or not

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {

// Memory has been successfully allocated

printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array

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

ptr[i] = i + 1;

// Print the elements of the array

printf("The elements of the array are: ");

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

printf("%d, ", ptr[i]);

// Get the new size for the array

n = 10;

printf("\n\nEnter the new size of the array: %d\n", n);


// Dynamically re-allocate memory using realloc()

ptr = realloc(ptr, n * sizeof(int));

// Memory has been successfully allocated

printf("Memory successfully re-allocated using realloc.\n");

// Get the new elements of the array

for (i = 5; i < n; ++i) {

ptr[i] = i + 1;

// Print the elements of the array

printf("The elements of the array are: ");

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

printf("%d, ", ptr[i]);

free(ptr);

return 0;

Output:

Enter number of elements: 5


Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,

Enter the new size of the array: 10


Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

Pointer to an Array | Array Pointer


#include<stdio.h>

int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
printf("%p\n", ptr);
return 0;
}

In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we
can also declare a pointer that can point to whole array instead of only one element of the
array. This pointer is useful when talking about multidimensional arrays.
Syntax:

data_type (*var_name)[size_of_array];

Example:

int (*ptr)[10];

Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher
precedence than indirection, it is necessary to enclose the indirection operator and pointer
name inside parentheses. Here the type of ptr is ‘pointer to an array of 10 integers’.
Note : The pointer that points to the 0th element of array and the pointer that points to the
whole array are totally different. The following program shows this:

Function Pointer in C
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions.
Following is a simple example that shows declaration and function call using function
pointer.

filter_none

edit

play_arrow

brightness_4

#include <stdio.h>

// A normal function with an int parameter

// and void return type

void fun(int a)

printf("Value of a is %d\n", a);

int main()

{
// fun_ptr is a pointer to function fun()

void (*fun_ptr)(int) = &fun;

/* The above line is equivalent of following two

void (*fun_ptr)(int);

fun_ptr = &fun;

*/

// Invoking fun() using fun_ptr

(*fun_ptr)(10);

return 0;

Output:

Value of a is 10

void pointer in C / C++


A void pointer is a pointer that has no associated data type with it. A void pointer can hold
address of any type and can be typcasted to any type.

int a = 10;

char b = 'x';

void *p = &a; // void pointer holds address of int 'a'

p = &b; // void pointer holds address of char 'b'

Advantages of void pointers:


1) malloc() and calloc() return void * type and this allows these functions to be used to
allocate memory of any data type (just because of void *)

int main(void)

{
// Note that malloc() returns void * which can be

// typecasted to any type like int *, char *, ..

int *x = malloc(sizeof(int) * n);

Note that the above program compiles in C, but doesn’t compile in C++. In C++, we must
explicitly typecast return value of malloc to (int *).

2) void pointers in C are used to implement generic functions in C. For example compare
function which is used in qsort().

Some Interesting Facts:


1) void pointers cannot be dereferenced. For example the following program doesn’t compile.

#include<stdio.h>

int main()

int a = 10;

void *ptr = &a;

printf("%d", *ptr);

return 0;

Output:

Compiler Error: 'void*' is not a pointer-to-object type

The following program compiles and runs fine.

#include<stdio.h>

int main()

int a = 10;

void *ptr = &a;

printf("%d", *(int *)ptr);


return 0;

Output:

10

2) The C standard doesn’t allow pointer arithmetic with void pointers. However, in GNU C it
is allowed by considering the size of void is 1. For example the following program compiles
and runs fine in gcc.

#include<stdio.h>

int main()

int a[2] = {1, 2};

void *ptr = &a;

ptr = ptr + sizeof(int);

printf("%d", *(int *)ptr);

return 0;

Output:

Vous aimerez peut-être aussi