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

Pointers in C

The document discusses pointers in C programming. It begins by defining a pointer as a variable that stores the address of another variable. It then provides examples of declaring pointer variables and using the address of (&) and value at address (*) operators with pointers. The document demonstrates how to get and set the value of a variable using its pointer, and explains some advantages of using pointers such as increasing program efficiency and accessing variables outside functions. It also discusses arrays of pointers and their syntax.

Uploaded by

Ankita Gholve
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Pointers in C

The document discusses pointers in C programming. It begins by defining a pointer as a variable that stores the address of another variable. It then provides examples of declaring pointer variables and using the address of (&) and value at address (*) operators with pointers. The document demonstrates how to get and set the value of a variable using its pointer, and explains some advantages of using pointers such as increasing program efficiency and accessing variables outside functions. It also discusses arrays of pointers and their syntax.

Uploaded by

Ankita Gholve
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Pointers in C

1
Pre-requisite
• Basics of the C programming language
– Data type
– Variable
– Array
– Function call
– Standard Input/Output
• e.g. printf(), scanf()

2
Outline
• Computer Memory Structure
• Addressing Concept
• Introduction to Pointer
• Pointer Manipulation
• Summary

3
WHAT IS POINTERS ?
• 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.

4
A simple example to understand how to access the address of a variable without pointers?

• In this program, we have a variable num of int type. The value


of num is 10 and this value must be stored somewhere in the
memory, right? A memory space is allocated for each variable
that holds the value of that variable, this memory space has
an address. For example we live in a house and our house has
an address, which helps other people to find our house. The
same way the value of the variable is stored in a memory
address, which helps the C program to find that value when it
is needed.

5
A simple example to understand how to access the address of a variable without pointers?

• So let’s say the address assigned to variable num is


0x7fff5694dc58, which means whatever value we would
be assigning to num should be stored at the location:
0x7fff5694dc58. See the diagram below.

6
Important point to note is: The data type of pointer and the
variable must match, an int pointer can hold the address of
int variable, similarly a pointer declared with float data type
can hold the address of a float variable. In the example
below, the pointer and the variable both are of int type.

7
• C Pointers – Operators that are used with Pointers
• Lets discuss the operators & and * that are used with Pointers in C.
• “Address of”(&) Operator
• 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.

8
• “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*/

• The above are the few examples of pointer declarations. If you need a pointer to store the address of integer variable then the
data type of the pointer should be int. Same case is with the other data types.

• By using * operator we can access the value of a variable through a pointer.


• For example:

• double a = 10;
• double *p;
• p = &a;

• *p would give us the value of the variable a. The following statement would display 10 as output.

• printf("%d", *p);
• Similarly if we assign a value to *pointer like this:
• *p = 200;
• It would change the value of variable a. The statement above will change the value of a from 10 to 200.
• 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;

10
• 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

11
12
• Lets take few more examples to understand it better –
• Lets say we have a char variable ch and a pointer ptr that holds the address of ch.

• char ch='a';
• char *ptr;

• Read the value of ch

• printf("Value of ch: %c", ch);


• or
• printf("Value of ch: %c", *ptr);

• Change the value of ch

• ch = 'b';
• or
• *ptr = 'b';

• The above code would replace the value ‘a’ with ‘b’.

13
• Can you guess the output of following C program?

• #include <stdio.h>
• int main()
• {
• int var =10;
• int *p;
• p= &var;
• printf ( "Address of var is: %p", &var);
• printf ( "\nAddress of var is: %p", p);
• printf ( "\nValue of var is: %d", var);
• printf ( "\nValue of var is: %d", *p);
• printf ( "\nValue of var is: %d", *( &var));
• /* Note I have used %p for p's value as it represents an address*/
• printf( "\nValue of pointer p is: %p", p);
• printf ( "\nAddress of pointer p is: %p", &p);
• return 0;
• }

14
• Can you guess the output of following C program?

• #include <stdio.h>
• int main()
• {
• int var =10;
• int *p;
• p= &var;
• printf ( "Address of var is: %p", &var);
• printf ( "\nAddress of var is: %p", p);
• printf ( "\nValue of var is: %d", var);
• printf ( "\nValue of var is: %d", *p);
• printf ( "\nValue of var is: %d", *( &var));
• /* Note I have used %p for p's value as it represents an address*/
• printf( "\nValue of pointer p is: %p", p);
• printf ( "\nAddress of pointer p is: %p", &p);
• return 0;
• }

15
• Output:

• Address of var is: 0x7fff5d027c58


• Address of var is: 0x7fff5d027c58
• Value of var is: 10
• Value of var is: 10
• Value of var is: 10
• Value of pointer p is: 0x7fff5d027c58
• Address of pointer p is: 0x7fff5d027c50

• https://beginnersbook.com/2014/01/c-pointers/https://www.google.co.in/search?q=POINTERS+SIMPLIFIED&ie=utf-8&oe=utf-8&client=firefox-b-ab&gfe_rd=cr&dcr=0&ei=smzUWp6-NqOl8weEh5j4Awhttps://www.thegeekstuff.com/2011/12/c-pointers-
fundamentals/

16
Advantages :

• Pointers reduce the length and complexity of a


program.
• They increase execution speed.
• A pointer enables us to access a variable that is
defined outside the function.
• Pointers are more efficient in handling the data
tables.
• The use of a pointer array of character strings results
in saving of data storage space in memory.

17
Advantages :

• Pointers used to access the address of the variable.


• Pointers increase the execution speed of program.
• Pointers are an important concept in data structures.
• Pointers are used for dynamic memory allocation.
• Pointers makes possible to return more than one value in
functions .
• Pointer enables us to access variables that are declared
outside the functions .
• Strings and arrays are more efficient with pointers.

18
Syntax for Pointer Declaration in C :

data_type *<pointer_name>;

Explanation :

data_type

Type of variable that the pointer points to


OR data type whose address is stored in pointer_name

Asterisk(*)

Asterisk is called as Indirection Operator


It is also called as Value at address Operator
It Indicates Variable declared is of Pointer type

19
Array of Pointers in C

Just like we can declare an array of int, float or


char etc, we can also declare an array of pointers,
here is the syntax to do the same.

Syntax: datatype *array_name[size];

Let's take an example:


int *arrop[5];
Here arrop is an array of 5 integer pointers. It means that
this array can hold the address of 5 integer variables, or in
other words, you can assign 5 pointer variables of type
pointer to int to the elements of this array.
20
The following program demonstrates how to use an array of pointers.

#include<stdio.h>
#define SIZE 10

int main()
{
int *arrop[3];
int a = 10, b = 20, c = 50, i;

arrop[0] = &a;
arrop[1] = &b;
arrop[2] = &c;

for(i = 0; i < 3; i++)


{
printf("Address = %d\t Value = %d\n", arrop[i], *arrop[i]);
}

return 0;
}

Expected Output:

Address = 2686764 Value = 10


Address = 2686760 Value = 20 21
Address = 2686756 Value = 50
How it works ?

Notice how we are assigning the addresses of a, b and c. In line 9, we


are assigning the address of variable a to the 0th element of the of the
array. Similarly, the address of b and c is assigned to 1st and 2nd
element respectively. At this point arr_of_pointer looks something like
this:

22
• Arrays are closely related to pointers in C programming but the important difference between them is that, a
pointer variable takes different addresses as value whereas, in case of array it is fixed.

• This can be demonstrated by an example:

• #include <stdio.h>
• int main()
• {
• char charArr[4];
• int i;

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


• {
• printf("Address of charArr[%d] = %u\n", i, &charArr[i]);
• }

• return 0;
• }

23
• When you run the program, the output will be:

• Address of charArr[0] = 28ff44


• Address of charArr[1] = 28ff45
• Address of charArr[2] = 28ff46
• Address of charArr[3] = 28ff47
• Notice, that there is an equal difference (difference of 1 byte) between any
two consecutive elements of array charArr.
• But, since pointers just point at the location of another variable, it can store
any address.

24
• Relation between Arrays and Pointers
• Consider an array:
• int arr[4];

• In C programming, name of the array always


points to address of the first element of an array.

25
• In the above example, arr and &arr[0] points to the address of the first element.

• &arr[0] is equivalent to arr

• Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.

• arr[0] is equivalent to *arr (value of an address of the pointer)

• Similarly,
• &arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
• &arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
• &arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
• ..
• &arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).

26
• Example: Program to find the sum of six numbers with arrays and pointers

• #include <stdio.h>
• int main()
• {
• int i, classes[6],sum = 0;
• printf("Enter 6 numbers:\n");
• for(i = 0; i < 6; ++i)
• {
• // (classes + i) is equivalent to &classes[i]
• scanf("%d",(classes + i));

• // *(classes + i) is equivalent to classes[i]


• sum += *(classes + i);
• }
• printf("Sum = %d", sum);
• return 0;
• }

27
• Output

• Enter 6 numbers:
• 2
• 3
• 4
• 5
• 3
• 4
• Sum = 21

28
• Example: Access Array Elements Using Pointers

• #include <stdio.h>

• int main()
• {
• int data[5], i;
• printf("Enter elements: ");

• for(i = 0; i < 5; ++i)


• scanf("%d", data + i);

• printf("You entered: \n");


• for(i = 0; i < 5; ++i)
• printf("%d\n", *(data + i));

• return 0;
• }

29
• A program that prints out pointers and the values they point to:

• #include <stdio.h>

• int main()
• {
• int a = 10, b = 2;
• int *p1, *p2;
• p1 = &a;
• p2 = &b;
• printf("%p %p \n", p1, p2);
• printf("%d %d \n", *p1, *p2);
• return 0;
• }

• This will produce following result:

• 0xbfffdac4 0xbfffdac0
• 10 2

30
• Passing pointers as parameters:

• A program that swaps integers using a function that accepts pointers to the integers to be swapped:

• #include <stdio.h>
• void swap(int * q,int * p)
• {
• int temp = *p;
• *p = *q;
• *q = temp;
• }
• int main()
• {
• int a = 10, b = 2, x = 3, y = 5;
• printf("a,b,x,y: %d,%d,%d,%d\n", a, b, x, y);
• swap(&x, &y);
• swap(&a, &b);
• printf("a,b,x,y: %d,%d,%d,%d\n", a, b, x, y);
• }

31
• It will produces following result:

• a,b,x,y: 10,2,3,5
• a,b,x,y: 2,10,5,3

32
• Common mistakes when working with pointers

• Suppose, you want pointer pc to point to the address of c. Then,

• int c, *pc;

• // Wrong! pc is address whereas,


• // c is not an address.
• pc = c;

• // Wrong! *pc is the value pointed by address whereas,


• // &c is an address.
• *pc = &c;

• // Correct! pc is an address and,


• // &c is also an address.
• pc = &c;

• // Correct! *pc is the value pointed by address and,


• // c is also a value (not address).
• *pc = c;

33
34
Program : Length of the String using Pointer

  
• #include<stdio.h>
• #include<conio.h>  int
•   string_ln(char*p) /*


int string_ln(char*);
p=&str[0] */
 
• void main() {  {


   char str[20];     int count = 0;
   int length;
•    clrscr();     while (*p != '\0') {


          count++;
   printf("\nEnter any string : ");
•    gets(str);        p++;


       }
   length = string_ln(str);
•    printf("The length of the given string %s is : %d", str, length);     return count;


   getch();  }
}

35
• Explanation :
• gets() is used to accept string with spaces.
• we are passing accepted string to the function.
• Inside function we have stored this string in pointer. (i.e base
of the string is stored inside pointer variable).
• Inside while loop we are going to count single letter and
incrementing pointer further till we get null character.

36
Program : How to Add Two Numbers Using Pointer ?

• #include<stdio.h>
•  
• int main() {
•    int *ptr1, *ptr2;
•    int num;
•  
•    printf("\nEnter two numbers : ");
•    scanf("%d %d", ptr1, ptr2);
•  
•    num = *ptr1 + *ptr2;
•  
•    printf("Sum = %d", num);
•    return (0);
• }

37
Write a ‘C’ Program to compute the sum of all elements stored in
an array using pointers

• #include<stdio.h>
• #include<conio.h>
• void main() {
•    int numArray[10];
•    int i, sum = 0;
•    int *ptr;
•  
•    printf("\nEnter 10 elements : ");
•  
•    for (i = 0; i < 10; i++)
•       scanf("%d", &numArray[i]);
•  
•    ptr = numArray; /* a=&a[0] */
•  
•    for (i = 0; i < 10; i++) {
•       sum = sum + *ptr;
•       ptr++;
•    }
•  
•    printf("The sum of array elements : %d", sum);
• } http://www.c4learn.com/c-programs/c-program-to-compute-sum-of-the-array-elements-using-pointers.html

38

You might also like