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

Unit_-4 PPT

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)
29 views

Unit_-4 PPT

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/ 54

STRUCTURES AND

POINTERS
Unit-4
Subject Name: Programming in C
Subject Code: U23CSTC01
Year/Sem/Sec: I / I / E
Prepared by:
Ms. V. SWATHILAKSHMI / AP /CSE
C Pointers:
• The pointer in C language is a variable which stores the address of another variable.
• This variable can be of type int, char, array, function, or any other pointer.
• The size of the pointer depends on the architecture.
• In 32-bit architecture the size of a pointer is 2 byte.

• Eg: int n = 10;


• int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of
type integer.
Syntax of C Pointers:
• The syntax of pointers is similar to the variable declaration in C, we use the ( * )
dereferencing operator in the pointer declaration.
datatype * ptr;
Where,
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
• The above syntax is used to define a pointer to a variable. We can also define pointers
to functions, structures, etc.
How to Use Pointers?
The use of pointers in C can be divided into three steps:
• Pointer Declaration
• Pointer Initialization
• Pointer Dereferencing
1. Pointer Declaration:
• In pointer declaration, we only declare the pointer but do not initialize it. To declare a
pointer, we use the ( * ) dereference operator before its name.

Example:
int *ptr;
• The pointer declared here will point to some random memory address as it is not
initialized. Such pointers are called wild pointers.
2. Pointer Initialization
• Pointer initialization is the process where we assign some initial value to the pointer
variable.
• We generally use the ( & ) addressof operator to get the memory address of a variable
and then store it in the pointer variable.
Eg:
int var = 10;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step.
This method is called pointer definition as the pointer is declared and initialized at the
same time.
3. Pointer Dereferencing:
• Dereferencing a pointer is the process of accessing the value stored in the memory
address specified in the pointer. We use the same ( * ) dereferencing operator that we
used in the pointer declaration.
Eg:
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
return 0;
}
Types of Pointers in C:
• Pointers in C can be classified into many different types based on the parameter on
which we are defining their types.

1. Integer Pointers
These are the pointers that point to the integer values.
• Syntax:
int *ptr;

• These pointers are pronounced as Pointer to Integer.


• Similarly, a pointer can point to any primitive data type. It can point to derived data
types such as arrays and user-defined data types such as structures.
2. Array Pointer
• Pointers and Array are closely related to each other. Even the array name is the
pointer to its first element. They are also known as Pointer to Arrays. We can create a
pointer to an array using the given syntax.

Syntax:
char *ptr = &array_name;
3. Structure Pointer:
• The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure.
It can be declared in the same way as we declare the other primitive data types.
Syntax: struct struct_name *ptr;

4. Function Pointers:
Function pointers point to the functions. They are different from the rest of the pointers in the
sense that instead of pointing to the data, they point to the code. Let’s consider a function
prototype – int func (int, char), the function pointer for this function will be

Syntax: int (*ptr)(int, char);

The syntax of the function pointers changes according to the function prototype.
5. Double Pointers:
• In C language, we can define a pointer that stores the memory address of another
pointer. Such pointers are called double-pointers or pointers-to-pointer. Instead of
pointing to a data value, they point to another pointer.
Syntax: datatype ** pointer_name;
6. NULL Pointer:
• The Null Pointers are those pointers that do not point to any memory location. They can
be created by assigning a NULL value to the pointer. A pointer of any type can be
assigned the NULL value.
Syntax
data_type *pointer_name = NULL; or
pointer_name = NULL

• Assign NULL to the pointers currently not in use.


7. Void Pointer:
• The Void pointers in C are the pointers of type void. It means that they do not have any
associated data type. They are also called generic pointers as they can point to any
type and can be typecasted to any type.

Syntax: void * pointer_name;

One of the main properties of void pointers is that they cannot be dereferenced.
8. Wild Pointers:
• The Wild Pointers are pointers that have not been initialized with something yet. These
types of C-pointers can cause problems in our programs and can eventually cause
them to crash.
• If values is updated using wild pointers, they could cause data abort or data
corruption.
Example:
int *ptr;
char *str;
9. Constant Pointers:
• In constant pointers, the memory address stored inside the pointer is constant and
cannot be modified once it is defined. It will always point to the same memory
address.

Syntax: data_type * const pointer_name;


10. Pointer to Constant:
• The pointers pointing to a constant value that cannot be modified are called pointers
to a constant. Here we can only access the data pointed by the pointer, but cannot
modify it. Although, we can change the address stored in the pointer to constant.

Syntax: const data_type * pointer_name;


POINTER ARITHMETICS IN C:
• Pointer Arithmetic is the set of valid arithmetic operations that can be performed on
pointers.
• The C pointer arithmetic operations are slightly different from the ones that we
generally use for mathematical calculations. These operations are:
• Increment/Decrement of a Pointer
• Addition of integer to a pointer
• Subtraction of integer to a pointer
• Subtracting two pointers of the same type
• Comparison of pointers
1. Increment/Decrement of a Pointer:
• Increment: It is a condition that also comes under addition. When a pointer is
incremented, it actually increments by the number equal to the size of the data type for
which it is a pointer.
For Example:
• If an integer pointer that stores address 1000 is incremented, then it will increment by
4(size of an int), and the new address will point to 1004. While if a float type pointer is
incremented then it will increment by 4(size of a float) and the new address will be
1004.
• Decrement: It is a condition that also comes under subtraction. When a pointer is
decremented, it actually decrements by the number equal to the size of the data type
for which it is a pointer.
#include <stdio.h> q--;

// pointer increment and decrement printf("q-- = %u\n", q); //q-- = 6422284 -4 // restored to original value

//pointers are incremented and decremented by the size of the data type
they point to
char c = 'a';
int main()
char *r = &c;
{
printf("r = %u\n", r); //r = 6422283
int a = 22;
r++;
int *p = &a;
printf("r++ = %u\n", r); //r++ = 6422284 +1 // 1 byte
printf("p = %u\n", p); // p = 6422288
r--;
p++;
printf("r-- = %u\n", r); //r-- = 6422283 -1 // restored to original value
printf("p++ = %u\n", p); //p++ = 6422292 +4 // 4 bytes

p--;
return 0;
printf("p-- = %u\n", p); //p-- = 6422288 -4 // restored to original value
}

float b = 22.22;

float *q = &b;

printf("q = %u\n", q); //q = 6422284

q++;

printf("q++ = %u\n", q); //q++ = 6422288 +4 // 4 bytes


2. Addition of Integer to Pointer:
• When a pointer is added with an integer value, the value is first multiplied by the size
of the data type and then added to the pointer.
For Example:
• Consider the same example as above where the ptr is an integer pointer that stores
1000 as an address. If we add integer 5 to it using the expression, ptr = ptr + 5, then,
the final address stored in the ptr will be ptr = 1000 + sizeof(int) * 5 = 1020.
// C program to illustrate pointer Addition printf("Pointer ptr2 before Addition: ");
#include <stdio.h> printf("%p \n", ptr2);

// Driver Code // Addition of 3 to ptr2


int main() ptr2 = ptr2 + 3;
{ printf("Pointer ptr2 after Addition: ");
// Integer variable printf("%p \n", ptr2);
int N = 4;
return 0;
// Pointer to an integer }
int *ptr1, *ptr2;

// Pointer stores the address of N


ptr1 = &N;
ptr2 = &N;
3. Subtraction of Integer to Pointer
• When a pointer is subtracted with an integer value, the value is first multiplied by the
size of the data type and then subtracted from the pointer similar to addition.

• For Example:
• Consider the same example as above where the ptr is an integer pointer that stores
1000 as an address. If we subtract integer 5 from it using the expression, ptr = ptr – 5,
then, the final address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.
// C program to illustrate pointer Subtraction printf("Pointer ptr2 before Subtraction: ");
#include <stdio.h> printf("%p \n", ptr2);

// Driver Code // Subtraction of 3 to ptr2


int main() ptr2 = ptr2 - 3;
{ printf("Pointer ptr2 after Subtraction: ");
// Integer variable printf("%p \n", ptr2);
int N = 4;
return 0;
// Pointer to an integer }
int *ptr1, *ptr2;

// Pointer stores the address of N


ptr1 = &N;
ptr2 = &N;
4. Subtraction of Two Pointers
• The subtraction of two pointers is possible only when they have the same data type.
The result is generated by calculating the difference between the addresses of the two
pointers and calculating how many bits of data it is according to the pointer data type.
The subtraction of two pointers gives the increments between the two pointers.

For Example:
• Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are subtracted.
The difference between addresses is 4 bytes. Since the size of int is 4 bytes, therefore
the increment between ptr1 and ptr2 is given by (4/4) = 1.
5. Comparison of Pointers:
• We can compare the two pointers by using the comparison operators in C. We can
implement this by using all operators in C >, >=, <, <=, ==, !=. It returns true for the
valid condition and returns false for the unsatisfied condition.
• Step 1: Initialize the integer values and point these integer values to the pointer.
• Step 2: Now, check the condition by using comparison or relational operators on
pointer variables.
• Step 3: Display the output
// C Program to illustrare pointer if (ptr1 == ptr2) {
comparision
printf("Pointer to Array Name and First
#include <stdio.h> Element "
"are Equal.");
int main() }
{ else {
// declaring array printf("Pointer to Array Name and First
Element "
int arr[5];
"are not Equal.");
}
// declaring pointer to array name
int* ptr1 = &arr;
return 0;
// declaring pointer to first element
}
int* ptr2 = &arr[0];
POINTER TO AN ARRAY:
#include<stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
printf("%p\n", ptr);
return 0;
}
In the above 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];

Here:
data_type is the type of data that the array holds.
var_name is the name of the pointer variable.
size_of_array is the size of the array to which the pointer will point.
Eg:
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.
EG:
// C program to understand difference between // Points to the whole array arr.

// pointer to an integer and pointer to an ptr = &arr;

// array of integers.

#include<stdio.h> printf("p = %p, ptr = %p\n", p, ptr);

int main() p++;

{ ptr++;

// Pointer to an integer

int *p; printf("p = %p, ptr = %p\n", p, ptr);

// Pointer to an array of 5 integers return 0;

int (*ptr)[5]; }

int arr[5];

// Points to 0th element of the arr.

p = arr;
• Here, p is pointer to 0th element of
the array arr, while ptr is a pointer
that points to the whole array arr.
• The base type of p is int while base
type of ptr is ‘an array of 5
integers’.
• We know that the pointer
arithmetic is performed relative to
the base size, so if we write ptr++,
then the pointer ptr will be shifted
forward by 20 bytes.
// C program to illustrate sizes of
// pointer of array
#include<stdio.h>
int main()
{
Output
int arr[] = { 3, 5, 6, 7, 9 };
• p = 0x7fff55adbff0, ptr = 0x7fff55adbff0
int *p = arr;
• *p = 3, *ptr = 0x7fff55adbff0
int (*ptr)[5] = &arr;
• sizeof(p) = 8, sizeof(*p) = 4
printf("p = %p, ptr = %p\n", p, ptr);
• sizeof(ptr) = 8, sizeof(*ptr) = 20
printf("*p = %d, *ptr = %p\n", *p, *ptr);
printf("sizeof(p) = %lu, sizeof(*p) = %lu\n",
sizeof(p), sizeof(*p));
printf("sizeof(ptr) = %lu, sizeof(*ptr) = %lu\n",
sizeof(ptr), sizeof(*ptr));
return 0;
}
POINTER TO FUNCTION:
• A function pointer in C is a variable that stores the address of a function. It allows you
to refer to a function by using its pointer and later call the function using that function
pointer.
• This provides flexibility in calling functions dynamically and can be useful in scenarios
where you want to select and call different functions based on certain conditions or
requirements.
• The function pointers in C are declared using the asterisk (*) operator to obtain the
value saved in an address.
Advantages of Function Pointers:
• A function pointer in C is useful to generate function calls to which they point. Hence,
the programmers can pass them as arguments. The function pointers enhance the
code’s readability.You can access many identical functions using a single line of code.

• Other prominent advantages of function pointer in C include passing functions as


parameters to other functions. Therefore, you can create generic functions which can
be used with any function provided that it possesses the right signature.
Syntax of Function Pointer in C:
• Here is the function pointer syntax in C.
return type (*ptr_name)(type1, type2...);
• Let’s look at an example:
int (*ip) (int);
*ip is a pointer in the above declaration. It points to a function that returns an int value
and also accepts an integer value as an argument.
• In C, you can pass pointers as function arguments and return pointers from the
function. If you want to pass pointers in the function, you just need to declare the
function parameter as a pointer type.
#include <stdio.h>
void increment(int *numb);
int main()
{
int numb = 10;
printf("The number before increment is: num = %d\n", numb);
increment(&numb);
printf("The output after increment is: num = %d\n", numb);
return 0;
}
void increment(int *numb) {
(*numb)++;
}
Output: The number before increment is: num = 10
The output after increment is: num = 11
REFERENCING AND DEREFERENCING OF
FUNCTION POINTER IN C:
Referencing a function pointer in C refers to assigning the address of a function to the
pointer using the ‘&’ operator. On the other hand, Dereferencing a function pointer in C
refers to accessing a function and invoking it with arguments using the ‘*’ operator.
Program that demonstrates passing pointers with functions:
#include <stdio.h>
// C program to swap two integers through pointers
void swap(int* x, int* y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int a = 50;
int b = 100;
printf("The numbers before swap: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("The numbers after swap: a = %d, b = %d\n", a, b);
return 0;
}
STRUCTURES IN C:

• The structure in C is a user-defined data type that can be used to group items of
possibly different types into a single type.
• The struct keyword is used to define the structure in the C programming language.
• The items in the structure are called its member and they can be of any valid data
type.
C Structure Declaration:
• We have to declare structure in C before using it in our program.
• In structure declaration, we specify its member variables along with their datatype.
• We can use the struct keyword to declare the structure in C.
Syntax:
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
• The above syntax is also called a structure template or structure prototype and no memory
is allocated to the structure in the declaration.
Example to define a structure for an entity employee in c.
struct employee
{ int id;
char name[20];
float salary;
};
C STRUCTURE DEFINITION:
• We can define structure variables using two methods:
1. Structure Variable Declaration with Structure Template

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;
2. Structure Variable Declaration after Structure Template
// structure declared beforehand
Struct structure_name variable1, variable2, .......;
Access Structure Members:
We can access structure members by using the ( . ) dot operator.
Syntax:
structure_name.member1;
strcuture_name.member2;
In the case where we have a pointer to the structure, we can also use the arrow operator
to access the members.
Initialize Structure Members:
Structure members cannot be initialized with the declaration. For example, the following
C program fails in the compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for the above error is simple. When a datatype is declared, no memory is
allocated for it. Memory is allocated only when variables are created.
We can initialize structure members in 3 ways which are as follows:
• Using Assignment Operator.
• Using Initializer List.
• Using Designated Initializer List.

1. Initialization using Assignment Operator:


struct structure_name str;
str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.
.
2. Initialization using Initializer List:
struct structure_name str = { value1, value2, value3 };
• In this type of initialization, the values are assigned in sequential order as they are
declared in the structure template.

3. Initialization using Designated Initializer List:


Designated Initialization allows structure members to be initialized in any order.
struct structure_name str = { .member1 = value1, .member2 = value2, .member3 =
value3 };
The Designated Initialization is only supported in C but not in C++.
struct str1 var1 = { 1, 'A', 1.00, "GeeksforGeeks" },
// C program to illustrate the use of structures
var2;
#include <stdio.h>

// declaring structure with name str1 struct str2 var3 = { .ff = 5.00, .ii = 5, .cc = 'a' };

struct str1 { // copying structure using assignment operator

int i; var2 = var1;


char c; printf("Struct 1:\n\ti = %d, c = %c, f = %f, s = %s\n",
float f;
var1.i, var1.c, var1.f, var1.s);
char s[30];
printf("Struct 2:\n\ti = %d, c = %c, f = %f, s = %s\n",
};
var2.i, var2.c, var2.f, var2.s);
// declaring structure with name str2
printf("Struct 3\n\ti = %d, c = %c, f = %f\n", var3.ii,
struct str2 {
var3.cc, var3.ff);
int ii;

char cc;

float ff; return 0;

} var; // variable declaration with structure template }


// Driver code

int main()

// variable declaration after structure template

// initialization with initializer list and designated

// initializer list
#include<stdio.h> //store second employee information
#include <string.h> e2.id=102;
struct employee strcpy(e2.name, “Karthik");
{ int id; e2.salary=126000;
char name[50]; //printing first employee information
float salary; printf( "employee 1 id : %d\n", e1.id);
}e1,e2; //declaring e1 and e2 variables for printf( "employee 1 name : %s\n", e1.name);
structure
printf( "employee 1 salary : %f\n", e1.salary);
int main( )
//printing second employee information
{
printf( "employee 2 id : %d\n", e2.id);
//store first employee information
printf( "employee 2 name : %s\n", e2.name);
e1.id=101;
printf( "employee 2 salary : %f\n", e2.salary);
strcpy(e1.name, “Suresh");//copying string into
return 0;
char array
}
e1.salary=56000;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy