0% found this document useful (0 votes)
8 views33 pages

C Programming: Strings and Pointers Guide

This document provides an overview of strings and pointers in C programming, explaining how strings are represented as character arrays and detailing various string handling functions available in the string.h library. It also covers pointer variables, their declaration, initialization, and usage in accessing memory addresses. Additionally, it includes examples of string manipulation functions like strcat(), strlen(), and strcpy(), as well as input/output functions for handling strings.
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)
8 views33 pages

C Programming: Strings and Pointers Guide

This document provides an overview of strings and pointers in C programming, explaining how strings are represented as character arrays and detailing various string handling functions available in the string.h library. It also covers pointer variables, their declaration, initialization, and usage in accessing memory addresses. Additionally, it includes examples of string manipulation functions like strcat(), strlen(), and strcpy(), as well as input/output functions for handling strings.
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

RV Institute of Technology & Management®

Module – 4
Strings and Pointers

4.1 Introduction

String is a sequence of characters that is treated as a single data item and terminated by null
character '\0'. Remember that C language does not support strings as a data type. A string is
actually one-dimensional array of characters in C language. These are often used to create
meaningful and readable programs.

For example: The string "hello world" contains 12 characters including '\0' character which is
automatically added by the compiler at the end of the string.

4.2 String taxonomy

⮚ Declaring and Initializing a string variables

There are different ways to initialize a character array variable.

char name[13] = "StudyTonight"; // valid character array initialization


char name[10] = {'L','e','s','s','o','n','s','\0'}; // valid initialization

Remember that when you initialize a character array by listing all of its characters separately
then you must supply the '\0' character explicitly.

Some examples of illegal initialization of character array are,

char ch[3] = "hell"; // Illegal


char str[4];
str = "hell"; // Illegal

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page1 | 33


RV Institute of Technology & Management®

⮚ String Input and Output

Input function scanf() can be used with %s format specifier to read a string input from the
terminal. But there is one problem with scanf() function, it terminates its input on the first white
space it encounters. Therefore if you try to read an input string "Hello World"
using scanf() function, it will only read Hello and terminate after encountering white spaces.

However, C supports a format specification known as the edit set conversion code %[..] that
can be used to read a line containing a variety of characters, including white spaces.

#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str); //scanning the whole string, including the white spaces
printf("%s", str);
}

Another method to read character string with white spaces from terminal is by using the gets()
function.

char text[20];
gets(text);
printf("%s", text);

4.3 . Operations on Strings


⮚ String Handling Functions

C language supports a large number of string handling functions that can be used to carry out
many of the string manipulations. These functions are packaged in string.h library. Hence, you
must include string.h header file in your programs to use these functions.

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page2 | 33


RV Institute of Technology & Management®

The following are the most commonly used string handling functions.

Method Description

strcat() It is used to concatenate(combine) two strings

strlen() It is used to show length of a string

strrev() It is used to show reverse of a string

strcpy() Copies one string into another

strcmp() It is used to compare two string

✔ strcat() function

strcat("hello", "world");

strcat() function will add the string "world" to "hello" i.e it will output helloworld.

✔ strlen() function

strlen() function will return the length of the string passed to it.

int j;
j = strlen("studytonight");
printf("%d",j);

Output: 12

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page3 | 33


RV Institute of Technology & Management®

✔ strcmp() function

strcmp() function will return the ASCII difference between first unmatching character of two
strings.

int j;
j = strcmp("study", "tonight");
printf("%d",j);

Output: -1

✔ strcpy() function

It copies the second string argument to the first string argument.

#include<stdio.h>
#include<string.h>

int main()
{
char s1[50];
char s2[50];

strcpy(s1, "StudyTonight"); //copies "studytonight" to string s1


strcpy(s2, s1); //copies string s1 to string s2
printf("%s\n", s2);
return(0);
}

Output: StudyTonight

✔ strrev() function

It is used to reverse the given string expression.

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page4 | 33


RV Institute of Technology & Management®

#include<stdio.h>
int main()
{
char s1[50];
printf("Enter your string: ");
gets(s1);
printf("\nYour reverse string is: %s",strrev(s1));
return(0);
}

Output:
Enter your string: studytonight
Your reverse string is: thginotyduts

n Sort Algorithm

Fig 3.8: Flowchart Selection Sort

1. What will be the output when you execute the below statements:

#include<stdio.h>

void main()

char arr[7]=”Network”;

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page5 | 33


RV Institute of Technology & Management®

printf(“%s”,arr);

Explanation:

Size of a character array should one greater than total number of characters in any string which it
stores. Inc every string has one terminating null character. This represents end of the string.

So in the string “Network” , there are 8 characters and they are ‘N’,’e’,’t’,’w’,’o’,’r’,’k’ and ‘\0’.
Size of array arr is seven. So array arr will store only first seven characters and it will note store null
character.

As we know %s in prinf statement prints stream of characters until it doesn’t get first null character.
Since array arr has not stored any null character so it will print garbage value.

5. What will be the output when you execute the below statements:

#include<stdio.h>

void main()

char arr[11]=”The African Queeen”;

printf(“%s”,arr);

Explanation:

Size of any character array cannot be less than the number of characters in any string which it has
assigned. Size of an array can be equal (excluding null character) or greater than but never less than. So
compilation error.

4.4. Miscellaneous string and character functions

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page6 | 33


RV Institute of Technology & Management®

4.4.1 strrev()

C Reverse String: strrev()


The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev()
function.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}

4.4.2 strlwr()

C String Lowercase: strlwr()


The strlwr(string) function returns string characters in lowercase. Let's see a simple example of strlwr()
function.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page7 | 33


RV Institute of Technology & Management®

printf("\nLower String is: %s",strlwr(str));


return 0;
}
4.4.3 strupr()

C String Uppercase: strupr()


The strupr(string) function returns string characters in uppercase. Let's see a simple example of
strupr() function.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}

[Link]()

The putchar(int char) method in C is used to write a character, of unsigned char type, to stdout.
This character is passed as the parameter to this method.
Syntax:
int putchar(int char)
Parameters: This method accepts a mandatory parameter char which is the character to be
written to stdout.
Return Value: This function returns the character written on the stdout as an unsigned char. It
also returns EOF when some error occurs.

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page8 | 33


RV Institute of Technology & Management®

C program to demonstrate putchar() method

#include <stdio.h>

int main()
{

// Get the character to be written


char ch = 'G';

// Write the Character to stdout


putchar(ch);

return (0);
}

4.4.5 getchar()

In this section, we will learn the getchar() function in the C programming language. A getchar() function
is a non-standard function whose meaning is already defined in the stdin.h header file to accept a single
input from the user. In other words, it is the C library function that gets a single character (unsigned char)
from the stdin. However, the getchar() function is similar to the getc() function, but there is a small
difference between the getchar() and getc() function of the C programming language. A getchar() reads a
single character from standard input, while a getc() reads a single character from any input stream.

Syntax

1. int getchar (void);

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page9 | 33


RV Institute of Technology & Management®

It does not have any parameters. However, it returns the read characters as an unsigned char in an int, and
if there is an error on a file, it returns the EOF at the end of the file.

Now we write several getchar() function programs to accept single characters in C and print them using
the putchar () function.

Read a single character using the getchar() function

Example :

Let's consider a program to take a single using the getchar() function in C.

#include <stdio.h>

#include <conio.h>

void main()

char c;

printf ("\n Enter a character \n");

c = getchar(); // get a single character

printf(" You have passed ");

putchar(c); // print a single character using putchar

4.4.6 gets()

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page10 | 33


RV Institute of Technology & Management®

The gets() function enables the user to enter some characters followed by the enter key. All the characters
entered by the user get stored in a character array. The null character is added to the array to make it a
string. The gets() allows the user to enter the space-separated strings. It returns the string entered by the
user.

Declaration

1. char[] gets(char[]);

Example :

Reading string using gets()


#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}

4.4.7 puts()
The puts() function is very much similar to printf() function. The puts() function is used to print the string
on the console which is previously read by using gets() or scanf() function. The puts() function returns an
integer value representing the number of characters being printed on the console. Since, it prints an
additional newline character with the string, which moves the cursor to the new line on the console, the
integer value returned by puts() will always be equal to the number of characters present in the string plus
1. int puts(char[])
example to read a string using gets() and print it on the console using puts().
#include<stdio.h>

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page11 | 33


RV Institute of Technology & Management®

#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
4.5 Arrays of strings
In C programming String is a 1-D array of characters and is defined as an array of characters. But an array
of strings in C is a two-dimensional array of character types. Each String is terminated with a null character
(\0). It is an application of a 2d array.
Syntax:
char variable_name[r] = {list of string};

 var_name is the name of the variable in C.


 r is the maximum number of string values that can be stored in a string array.
 c is a maximum number of character values that can be stored in each string array.
Example :

C Program to print Array


// of strings
#include <stdio.h>

// Driver code
int main()
{
char arr[3][10] = {"Geek",

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page12 | 33


RV Institute of Technology & Management®

"Geeks", "Geekfor"};
printf("String array Elements are:\n");

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


{
printf("%s\n", arr[i]);
}
return 0;
}

Pointers
4.6 Introduction to Pointers:
Pointer is a derived data type in C language. The variables that holds memory addresses are called
pointer variables. Pointers are used in C program to access the memory and manipulate the address.

The pointer operators are & (Address operator) and *(Dereferencing operator or Indirection
operator).

The actual location of a variable in memory is system dependent. A programmer cannot know the
address of a variable immediately. We can retrieve the address of a variable by using the address of
(&) operator. Let’s look at the following example:

int a=10;

int *p;

p=&a;

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page13 | 33


RV Institute of Technology & Management®

In the above example, let the variable a is stored at memory address 5000. This can be retrieved by
using the address of operator as &a. So the value stored in variable p is 5000 which is the memory
address of variable a. So, both the variable a, and p point to the same memory location.

4.7 Declaring and initializing of pointer variables:

Declaration of Pointer Variables:


Since pointer variables contain addresses that belong to a separate data type, they must be declared
as pointers before we use them. The declaration of a pointer variable has the following form:

General Form:
datatype *pt_name;

This tells the compiler three things about the variable pt_name.
1. The asterisk(*) tells that the variable pt_name is a pointer variable.

2. pt_name needs a memory location.

3. pt_name points to variable of type data type.

Different forms of declaring integer pointer variables:

Ex: int *p;


int* p;
int * p;

Declaration of float pointer variable


Ex: float *p;

Declaration of char pointer variable


Ex: char *p;

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page14 | 33


RV Institute of Technology & Management®

Declaration of double pointer variable


Ex: double *p;

Initialization of Pointer Variables:


int i, *p1=&i; //Address of variable i is stored in pointer variable p1

int *p1=&i,i; ----------> Wrong

Pointer variables can be initialized with the values NULL and 0.


Ex: int *p=NULL;
int *p=0;

Same Pointer can point to different data variables in different statements.


Ex: int x, y, z,*p;
p=&x; p=&y; p=&z;

Different pointers can be used to point to same data variable.


Ex: int x;
int *p1=&x;
int *p2=&x;
int *p3=&x;

Accessing a variable using pointer

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page15 | 33


RV Institute of Technology & Management®

Once a pointer has been assigned the address of a variable, the question remains as to how to access
the value of the variable using the pointer. This is done by using *(asterisk), usually known as the
indirection operator.

int i,*p,n; // p is a pointer variable and i is a integer variable


i=10;
p=&i; // p holds the address of variable i
n=*p; // Returns the value of variable i
This is equivalent to n=*&i; or n=i.

Chain of Pointers
Pointer can point to another pointer.
Ex:
main()
{
int x, *p1,**p2;
x=100;
p1=&x;
p2=&p1;
printf (“%d”,**p2); //Output is 100
}

In this example, pointer variable p2 contains the address of the pointer variable p1, which points
to the location that contains the desired value. This is known as multiple indirections.

Pointer Expressions
1) Pointer variables can be used in expressions.
Ex: int *p1,*p2;
y=*p1 * *p2;

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page16 | 33


RV Institute of Technology & Management®

Sum=Sum+ *p1;
Z=5* -*p2/ *p1;

2) Short hand operators can be used with pointers.


Ex: int *p1,*p2;
p1++;
-p2;
sum += *p2;

3) Pointers can be compared using relational operators.


Ex: p1>p2,
p1==p2,
p1!=p2

Pointer Increments and Scale Factor


When a pointer is incremented, its value is increased by the length of the datatype it points to. This
length is called scale factor.
Ex:
int *p; i=10;
p=&i;
p=p+1;

In this example, if the address value of i is 2800, then pointer variable p holds the address of i, i.e.
2800. If the pointer variable is incremented by 1, it becomes 2802.

Pointers and Character Strings

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page17 | 33


RV Institute of Technology & Management®

A pointer may be defined as pointing to a character string. A pointer which pointing to an array
which content is string, is known as pointer to array of strings.
#include <stdio.h>
main()
{
char *text_pointer = "Good morning!";
for( ; *text_pointer != '\0'; ++text_pointer)
printf("%c", *text_pointer);
}

4.8 Types of Pointers

There are different types of pointers which are as follows −


 Null pointer
 Void pointer
 Wild pointer
 Dangling pointer

Null Pointer
You create a null pointer by assigning the null value at the time of pointer declaration.

This method is useful when you do not assign any address to the pointer. A null pointer always
contains value 0.

Example
Example –

#include <stdio.h>

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page18 | 33


RV Institute of Technology & Management®

int main(){

int *ptr = NULL; //null pointer

printf("The value inside variable ptr is:


%d",ptr);

return 0;

Void Pointer
It is a pointer that has no associated data type with it. A void pointer can hold addresses of any
type and can be typecast to any type.
It is also called a generic pointer and does not have any standard data type.
It is created by using the keyword void.
Example:

#include <stdio.h>

int main(){

void *p = NULL; //void pointer

printf("The size of pointer is:%d


",sizeof(p)); //size of p depends on compiler

return 0;

Wild Pointer

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page19 | 33


RV Institute of Technology & Management®

Wild pointers are also called uninitialized pointers. Because they point to some arbitrary memory location
and may cause a program to crash or behave badly.

This type of C pointer is not efficient. Because they may point to some unknown memory location which
may cause problems in our program. This may lead to the crashing of the program.

It is advised to be cautious while working with wild pointers.

Example
Following is the C program for the wild pointer −

#include <stdio.h>

int main(){

int *p; //wild pointer

printf("
%d",*p);

return 0;

Dangling pointers

The most common bugs related to pointers and memory management is dangling/wild pointers.
Sometimes the programmer fails to initialize the pointer with a valid address, then this type of
initialized pointer is known as a dangling pointer in C.
Dangling pointer occurs at the time of the object destruction when the object is deleted or de-
allocated from memory without modifying the value of the pointer. In this case, the pointer is
pointing to the memory, which is de-allocated. The dangling pointer can point to the memory,
which contains either the program code or the code of the operating system. If we assign the value
to this pointer, then it overwrites the value of the program code or operating system instructions;

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page20 | 33


RV Institute of Technology & Management®

in such cases, the program will show the undesirable result or may even crash. If the memory is
re-allocated to some other process, then we dereference the dangling pointer will cause the
segmentation faults.

In the above figure, we can observe that the Pointer 3 is a dangling pointer. Pointer 1 and Pointer
2 are the pointers that point to the allocated objects, i.e., Object 1 and Object 2,
respectively. Pointer 3 is a dangling pointer as it points to the de-allocated object.

Let's understand the dangling pointer through some C programs.

Using free() function to de-allocate the memory.

#include <stdio.h>
int main()
{
int *ptr=(int *)malloc(sizeof(int));
int a=560;
ptr=&a;
free(ptr);
return 0;

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page21 | 33


RV Institute of Technology & Management®

In the above code, we have created two variables, i.e., *ptr and a where 'ptr' is a pointer and 'a' is a
integer variable. The *ptr is a pointer variable which is created with the help of malloc() function. As
we know that malloc() function returns void, so we use int * to convert void pointer into int pointer.

The statement int *ptr=(int *)malloc(sizeof(int)); will allocate the memory with 4 bytes shown in
the below image:

The statement free(ptr) de-allocates the memory as shown in the below image with a cross sign, and
'ptr' pointer becomes dangling as it is pointing to the de-allocated memory.

If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted memory. Therefore, we
can say that ptr is not a dangling pointer, as shown in the below image:

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page22 | 33


RV Institute of Technology & Management®

If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted memory. Therefore, we
can say that ptr is not a dangling pointer, as shown in the below image:

Variable goes out of the scope

When the variable goes out of the scope then the pointer pointing to the variable becomes a dangling
pointer.

#include<stdio.h>

int main()

char *str;

char a = ?A?;

str = &a;

// a falls out of scope

// str is now a dangling pointer

printf("%s", *str);

In the above code, we did the following steps:

o First, we declare the pointer variable named 'str'.

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page23 | 33


RV Institute of Technology & Management®

o In the inner scope, we declare a character variable. The str pointer contains the address of the
variable 'a'.

o When the control comes out of the inner scope, 'a' variable will no longer be available, so str points
to the de-allocated memory. It means that the str pointer becomes the dangling pointer.

Function call

Now, we will see how the pointer becomes dangling when we call the function.

Let's understand through an example.

#include <stdio.h>

int *fun(){

int y=10;

return &y;

int main()

int *p=fun();

printf("%d", *p);

return 0;

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page24 | 33


RV Institute of Technology & Management®

o First, we create the main() function in which we have declared 'p' pointer that contains the return
value of the fun().

o When the fun() is called, then the control moves to the context of the int *fun(), the fun() returns
the address of the 'y' variable.

o When control comes back to the context of the main() function, it means the variable 'y' is no
longer available. Therefore, we can say that the 'p' pointer is a dangling pointer as it points to the
de-allocated memory.

Output :

Let's represent the working of the above code diagrammatically

Example 2:

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page25 | 33


RV Institute of Technology & Management®

#include <stdio.h>

int *fun()

static int y=10;

return &y;

int main()

int *p=fun();

printf("%d", *p);

return 0;

The above code is similar to the previous one but the only difference is that the variable 'y' is static.
We know that static variable stores in the global memory.

Output

Now, we represent the working of the above code diagrammatically.

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page26 | 33


RV Institute of Technology & Management®

The above diagram shows the stack memory. First, the fun() function is called, then the control moves
to the context of the int *fun(). As 'y' is a static variable, so it stores in the global memory; Its scope
is available throughout the program. When the address value is returned, then the control comes back
to the context of the main(). The pointer 'p' contains the address of 'y', i.e., 100. When we print the
value of '*p', then it prints the value of 'y', i.e., 10. Therefore, we can say that the pointer 'p' is not a
dangling pointer as it contains the address of the variable which is stored in the global memory.

4.8 Passing arguments to functions using pointers

Just like any other argument, pointers can also be passed to a function as an argument. Lets take an
example to understand how this is done.

Example: Passing Pointer to a Function in C Programming

In this example, we are passing a pointer to a function. When we pass a pointer as an argument instead
of a variable then the address of the variable is passed instead of the value. So any change made by
the function using the pointer is permanently made at the address of passed variable. This technique
is known as call by reference in C.

Try this same program without pointer, you would find that the bonus amount will not reflect in the
salary, this is because the change made by the function would be done to the local variables of the
function. When we use pointers, the value is changed at the address of variable

#include <stdio.h>

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page27 | 33


RV Institute of Technology & Management®

void salaryhike(int *var, int b)

*var = *var+b;

int main()

int salary=0, bonus=0;

printf("Enter the employee current salary:");

scanf("%d", &salary);

printf("Enter bonus:");

scanf("%d", &bonus);

salaryhike(&salary, bonus);

printf("Final salary: %d", salary);

return 0;

Example 2: Swapping two numbers using Pointers

This is one of the most popular example that shows how to swap numbers using call by reference.

Try this program without pointers, you would see that the numbers are not swapped. The reason is
same that we have seen above in the first example.

#include <stdio.h>

void swapnum(int *num1, int *num2)

int tempnum;

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page28 | 33


RV Institute of Technology & Management®

tempnum = *num1;

*num1 = *num2;

*num2 = tempnum;

int main( )

int v1 = 11, v2 = 77 ;

printf("Before swapping:");

printf("\nValue of v1 is: %d", v1);

printf("\nValue of v2 is: %d", v2);

/*calling swap function*/

swapnum( &v1, &v2 );

printf("\nAfter swapping:");

printf("\nValue of v1 is: %d", v1);

printf("\nValue of v2 is: %d", v2);

4.9 Pointers – Example program


Program Print the Address of the Character Array
#include<stdio.h>
int main()

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page29 | 33


RV Institute of Technology & Management®

{
int i;
char *arr[4] = {"C","C++","Java","VBA"};
char *(*ptr)[4] = &arr;
for(i=0;i<4;i++)
printf("Address of String %d : %u\n",i+1,(*ptr)[i]);
return 0;
}
Output:
Address of String 1 = 178
Address of String 2 = 180
Address of String 3 = 184
Address of String 4 = 189

Program to Print Contents of character array


#include<stdio.h>
int main()
{
int i;
char *arr[4] = {"C","C++","Java","VBA"};
char *(*ptr)[4] = &arr;
for(i=0;i<4;i++)
printf("String %d : %s\n",i+1,(*ptr)[i]);
return 0;
}
Output :
String 1 = C
String 2 = C++

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page30 | 33


RV Institute of Technology & Management®

String 3 = Java
String 4 = VBA

Advantages of Pointers:
1. Pointers can be used to return multiple values from User Defined Function.

2. It allows C language to support dynamic memory management.

3. It increases the execution speed and reduce the program execution time.

4. It provides an efficient tool for manipulating dynamic data structures such as structures, linked
lists, queues, stacks and trees.

Example Questions:
1) Write a program to find the sum of all elements stored in an array using pointers?
main( )
{
int *p,sum,i;
int a[5]={10,20,30,40,50};
i=0;
p=a;
while(a<5)
{
printf(“%d%d%u”, i,*p,p);
sum=sum+*p;
i++; p++;
}
printf(“%d”, sum);
}
2) Find the output of the following program: Assume the address values of m, ptr and y are
2000, 3000 and 4500 respectively.

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page31 | 33


RV Institute of Technology & Management®

main()
{
int m;
int *ptr;
m=15;
ptr=&m;
y=*ptr;
printf(“Value of m is %d\n\n”, m);
printf(“%d is stored at address %u \n”, m,&m);
printf(“%u%u \n”, ptr, &ptr);
printf(“%d is stored at address %u \n”, y, &y);
*ptr=30;
printf(“\n Now m=%d\n”,x);
}
Output:
15
15 is stored at address 2000
2000 3000
15 is stored at address 4500
Now m=30

3) Write a program to perform the arithmetic operations using pointers


main()
{
int a, b,*p1,*p2;
int sum,diff,prod,div;
a=200, b=10;
p1=&a;p2=&b;

I & II-Semester, Problem Solving through Programming(21PSP13/23) Page32 | 33


RV Institute of Technology & Management®

sum=*p1 + *p2;
diff=*p1 - *p2;
prod=*p1 * *p2;
div=*p1 / *p2;
printf(“%d%d%d%d”, sum,diff,prod,div);
}

Output:
210
190
2000
20

I & II-Semester, Problem solving through Programming (21PSP13/23)


Page1 | 33

You might also like