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

BPOPS103/203 Module 4 Notes

This document covers the concepts of strings and pointers in C programming. It explains how to declare and initialize string variables, read and write strings, and utilize various string functions such as strcat, strcmp, and strcpy. Additionally, it introduces pointers, their declaration, and basic operations, emphasizing their importance in memory management and dynamic allocation.

Uploaded by

Hamza Hafeel
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)
23 views

BPOPS103/203 Module 4 Notes

This document covers the concepts of strings and pointers in C programming. It explains how to declare and initialize string variables, read and write strings, and utilize various string functions such as strcat, strcmp, and strcpy. Additionally, it introduces pointers, their declaration, and basic operations, emphasizing their importance in memory management and dynamic allocation.

Uploaded by

Hamza Hafeel
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/ 18

Module-IV Strings and Pointers

Strings

String variable:
A string is an array of characters. Any group of characters defined between
double quotation marks is called a constant string.
String in C programming is a sequence of characters terminated with a null character „\0‟.
Strings are defined as an array of characters. The difference between a character array and a
string is the string is terminated with a unique character „\0‟.
Example:
“Good Morning Everybody”

Character strings are often used to build meaningful and readable programs.
A string variable is any valid C variable name and is always declared as an array.

Declaring and initializing string variables:


The general form of string variable is
char string_name[size];
The size determines the number of characters in the string-name.
Some examples are:
char state[10];
char name[30];
When the compiler assigns a character string to a character array, it automatically supplies a null
character(„\0‟) at the end of the string.
Character arrays may be initialized when they are declared. C permits a character array to be
initialized in either of the following two forms:

char state[10]=” KARNATAKA”;


char state[10]={„K‟,‟A‟,‟R‟,‟N‟,‟A‟,‟T‟,‟A‟,‟K‟,‟A‟,‟\0‟};

The reason that state had to be 10 elements long is that the string KARNATAKA contains 10
characters and one element space is provided for the null terminator.

C also permits us to initialize a character array without specifying the number of


elements.
For example, the statement

char string[ ] ={„H‟, „E‟, „L‟, „L‟, „O‟ ,‟\0‟};

Defines the array string as a six element array.


Reading and writing strings:
To read a string of characters input function scanf can be used with %s format
specification.
Example:
char add[20];
scanf(“%s”, add);

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 1


Note that unlike previous scanf calls, in the case of character arrays, the &(ampersand) is not
required before the variable name. The scanf function automatically terminates the string that is
read with a null character and therefore the character array should be large enough to hold the
input string plus the null character.

Program to read a series of words using scanf function


main()
{
char text1[50],text2[50],text3[50],text4[50];
printf(“Enter text:\n”);
scanf(“%s %s”, text1,text2);
scanf(“%s”, text3);
scanf(“%s”, text4);
printf(“\n”);
printf(“text1= %s\n text2=%s\n”, text1,text2);
printf(“text3= %s\n text4= %s\n”, text3,text4);
}

Writing strings:
The printf function with %s can be used to display an array of characters that is
terminated by the null character.
Example:
printf(“%s”, text);
Can be used to display the entire contents of the array name.

Using the puts( ) and gets( ) Functions:


The gets( ) function reads a string from keyboard. This function stops reading the string
only when we press the ENTER key from the keyboard. The gets( ) function is similar to the
scanf( ) function. The difference between the gets( ) and scanf( ) function is that the gets( )
function can read the whole sentence, which is a combination of multiple words; while the
scanf( ) function can read the character until a space or a newline character is encountered in a
sentence. The following program shows that the scanf( ) function cannot store the string data of
multiple words in a variable.
#include<stdio.h>
main( )
{
char msg[70];
printf(“enter the message”);
scanf(“%s”,msg);
printf(“%s”,msg);
}
Output:
enter the message
welcome to computer lab
welcome

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 2


In the above program, the scanf( ) function does not read multiple words into an array. This is
because when we enter a space after the word welcome, the scanf( ) function considers it as the
end of string and do not consider any character typed after it.
The gets ( ) function in place of scanf ( ) function is used to overcome this problem of reading
multiple words into an array.
The puts( )function, on the other hand, prints a string or a value stored in a variable to the
console in the next line. The following program shows the use of gets( ) and puts( ) functions.
#include<stdio.h>
#define length 100
main( )
{
char student_name1[length]=”John”;
char student_name2[length]=”Alex”;
puts(“Name of 1st student:”);
puts(student_name1);
puts(“Name of 2nd student:”);
puts(student_name2);
puts(“Enter a new name for the 2nd student”);
gets(student_name2);
puts(student_name1);
puts(student_name2);
}
Output:
Name of 1st student:
John
Name of 2nd student:
Alex
Enter a new name for the 2nd student
Marc
John
Marc
In the above program, the puts( ) function prints a string, Name of 1st student: to the console.
The value stored in the student_name1 array is printed by using the puts() function. Another
string, Name of 2nd student: is printed along with the value stored in the student_name2 array by
using the puts( ) function. The program prompts us to enter a new name for the 2nd student. The
entered value gets stored in the student_name2 array by using the gets( ) function. At the end, the
values stored in the student_name1 and student_name2, arrays are printed to the console.

String functions:
C library supports a large number of string functions. The list given below depicts the
string functions

Function Action
strcat( ) concatenates two strings
strcmp( ) compares two strings
strcpy( ) copies one string with another

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 3


strlen( ) finds the length of a string.
strupr( ) used to convert the letters of string to uppercase
strlwr( ) used to convert the letters of string to lowercase
strrev( ) used to reverse the string

String Concatenation :strcat( ) function:

The strcat function joins two strings together. The general form is

strcat(string1,string2);

string1 and string2 are character arrays. When the function strcat is executed. String2 is
appended to string1. It does so by removing the null character at the end of string1 and placing
string2 from there. The string at string2 remains unchanged.
Example
#include<string.h>
int main()
{
char src[20]= “ before”;
char dest[20]= “after ”;
strcat(dest, src);
puts(dest);
return 0;
}
The output will be: after before

String comparison: strcmp( ) function:

The strcmp function compares two strings identified by the arguments and has a value 0
if they are equal.
The general form is :
strcmp(string1,string2);
String1 and string2 may be string variables or string constants.
On comparing the return value be determined basis the strings setup as shown below.
The function returns a definite value that may be either 0, >0, or <0. In this function, the two
values passed are treated as case sensitive means „A‟ and „a‟ are treated as different letters.
The values returned by the function are used as:
i) 0 is returned when two strings are the same
ii) If str1<str2 then a negative value is returned
iii) If str1>str2 then a positive value is returned
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]=”copy”;

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 4


char str2[]=”Trophy”;
int I,j,k;
i=strcmp(str1, “copy”);
j=strcmp(str1, str2);
k-strcmp(str1, “f”);
printf(“\n %d %d %d”,I,j,k);
return 0;
}
Output: 0 -1 1

String copying: strcpy( ) function:


The strcpy() function works almost like a string-assignment operator. The general format is
strcpy(string1,string2);
It copies the contents of string2 to string1. string2 may be a character variable or a string
constant.
Example:
#include<string.h>
int main()
{
char src[20]= “ Destination”;
char dest[20]= “”;
printf(“\n source string is = %s”, src);
printf(“\n destination string is = %s”, dest);
strcpy(dest, src);
printf (“\ntarget string after strcpy() = %s”, dest);
return 0;
}
Output
Source string is = Destination
Target string is =
Target string after strcpy() = Destination

Finding the length of a string: strlen( ) function:


This function counts and returns the number of characters in a string.
The general syntax is n=strlen(string);
Where n is an integer variable which receives the value of the length of the string. The
argument may be a string constant. The counting ends at the first null character.
Example:
#include<stdio.h>
int main()
{
int length;
char s[20] = “We are Here”;
length=strlen(s);
printf(“\Length of the string is = %d \n”, length);
return 0;

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 5


}
Length of the string is = 11

strlwr( )/ strupr( ) Functions:


Sometimes you may need to convert the lowercase letters of any string to the uppercase or
vice-versa. As it can be understood the lwr stands for lowercase and upr stands for uppercase.
For this purpose there are two direct string functions in C, they can be used to perform the
conversions either from upper to lower case or vice-versa. Here, we have explained an
example of the same:
#include<stdio.h>
#include<string.h>
int main()
{
char str[]=”CONVERT me To the Lower Case”;
printf(“%s\n”, strlwr(str));
return 0;
}
Output: convert me to the lower case
Similarly, if we will use the strupr function in place of strlwr, then all the content will be
converted to the upper case letters. We can use the strupr function, defined in the string
header file. Through this function, all letters of the string are converted, that too without any
long manual procedure.

Function strrev()
If you want to reverse any string without writing any huge or extensive program manually,
then you can use this function. The rev in the strrev() stands for reverse and it is used to
reverse the given string. Function strrev() is used to reverse the content of the string. Strrev
function is used to check the nature of the string, whether the given string is a palindrome or
not. Several other uses and applications are also present in the string reverse function. One of
its uses is given below:
#include<stdio.h>
#include<string.h>
int main()
{
char temp[20]=”Reverse”;
printf(“String before reversing is : %s\n”, temp);
printf(“String after strrev() :%s”, strrev(temp));
return 0;
}

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 6


Character functions in C
Character functions need ctype.h header file to be included in the program.
Different character functions provided by C Language are:
1. isalpha():
This function checks whether the character variable/constant contains alphabet or
not.
2. isdigit()
This function checks whether the character variable/ constant contains digit or not.
3. isalnum()
This function checks whether the character variable/constant contains an alphabet
or digit.
4. ispunct()
This function checks whether the character variable/constant contains a punctuator
or not. Punctuators are comma, semicolon etc.
5. isspace()
This function checks whether the character variable/constant contains a space or
not.
Program to demonstrate the use of character functions.
#include<ctype.h>
#include<stdio.h>
int main()
{
char n;
printf("\nEnter a character=");
n=getche();
if(isalpha(n))
printf("\nYou typed an alphabet");
if(isdigit(n))
printf("\nYou typed a digit");
if(isalnum(n))
printf("\nYou typed an alphabet or digit");
if(isspace(n))
printf("\nYou typed a blank space");
if(ispunct(n))
printf("\nYou typed punctuator");
return(0);
}

Output

Enter a character=A
You typed an alphabet

6. isupper()

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 7


This function checks whether the character variable/constant contains an capital
letter alphabet or not.
7. islower()
This function checks whether the character variable/constant contains a lowercase
alphabet or not.

8. toupper()
This function converts lowercase alphabet into uppercase alphabet.
9. tolower()
This function converts an uppercase alphabet into lowercase alphabet.
Program to use of islower,isupper,tolower(),toupper().
#include<ctype.h>
#include<stdio.h>
int main()
{
char n;
printf("\nEnter an alphabet=");
n=getche();
if(islower(n))
n=toupper(ch);
else
ch=tolower(ch);
printf("\nNow alphabet=%c",n);
return(0);
}

Output

Enter an alphabet=A
Now alphabet=a

Pointers:
Pointers in C are easy and fun to learn. Some C programming tasks are performed more
easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed
without using pointers. As we know, every variable is a memory location and every memory
location has its address defined which can be accessed using ampersand (&) operator, which
denotes an address in memory. Consider the following example, which will print the address of
the variables defined:
#include <stdio.h>

int main ()
{

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 8


int var1;
char var2[10];

printf("Address of var1 variable: %x\n", &var1 );


printf("Address of var2 variable: %x\n", &var2 );

return 0;
}

When the above code is compiled and executed, it produces result something as follows:

Address of var1 variable: bff5a400


Address of var2 variable: bff5a3f6

Basics of pointers:
A pointer is a variable whose value is the address of another variable, i.e., direct address
of the memory location. In other words, a pointer is a variable that represent the location (rather
than the value) of a data item, such as a variable or an array element. It is a variable that holds a
memory address. This address is the location of another variable or an array element in memory.
For example, if one variable contains the address of another variable, the first variable is said to
point to the second.

Declaring Pointer Variables:


Like any variable or constant, we must declare a pointer before we can use it to store any
variable address. The general form of a pointer variable declaration is:

type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of
the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use
for multiplication. However, in this statement the asterisk is being used to designate a variable as
a pointer. Following are the valid pointer declaration:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.

For example: int *ptr;

In the above example, ptr is the name of our variable. The „*‟ informs the compiler that we want
a pointer variable. i.e. to set aside number of bytes required to store an address in memory. The

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 9


int says that we intend to use our pointer is said to “point to” an integer. However, note that
when we wrote int k; we did not give k a value. Similarly, ptr has no value, this means that we
haven‟t stored an address in it in the above declaration.

Initializing Pointer Variables:

The process of assigning the address of a variable to a pointer variable is known as


initialization of pointer variable.
Example: ptr=&k;
The & operator retrieves the address of k, even though k is on the right hand side of the
assignment operator = and copies that to the contents of our pointer ptr. Now ptr is said to
“point to” k. The only requirement here is that the variable k must be declared before the
initialization takes place. We must ensure that the pointer variables always point to the
corresponding type of data. Here are few examples:
int i, *p, *r; /* integer variable and pointer declarations */
float f, *q; /* float variable and pointer declarations */
p=&i; /* Correct initialization of integer pointer */
r=p; /* Correct initialization we can assign value of other pointer variable to pointer
variable */
q=&f; /* Correct initialization of float pointer */
p=&f; /* Incorrect initialization since data type does not match */
Pointer variables can point to numeric or character variable, arrays, functions or other pointer
variables. Thus a pointer variable can be assigned the address of an ordinary variable or it can be
assigned the value of other pointer variable provided both pointer variables are of same type.

Types of Pointer:
There are majorly four types of pointers, they are:
 Null Pointer
 Void Pointer
 Wild Pointer
 Dangling Pointer

Null Pointer:
A pointer can also be initialized by assigning a NULL value. It is always a good practice
to assign a NULL value to a pointer variable in case we do not have exact address to be assigned.
This is done at the time of variable declaration. A pointer that is assigned NULL is called
a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program:

#include <stdio.h>
int main ()
{

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 10


int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );

return 0;
}

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

The value of ptr is 0

Void Pointer:
When a pointer is declared with a void keyword, then it is called a void pointer. To print the
value of this pointer, you need to typecast it.
Syntax:
void *var;
Example:
#include<stdio.h>
int main()
{
int a=2;
void *ptr;
ptr= &a;
printf("After Typecasting, a = %d", *(int *)ptr);
return 0;
}

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

After Typecasting, a=2

Wild Pointer:
A wild pointer is only declared but not assigned an address of any variable. They are very tricky,
and they may cause segmentation errors.
Example:
#include<stdio.h>

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 11


int main()
{
int *ptr;
printf(“ptr=%d”,*ptr);
return 0;
}

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

Segmentation fault (core dumped)

Dangling Pointer
 Suppose there is a pointer p pointing at a variable at memory 1004. If you deallocate this
memory, then this p is called a dangling pointer.
 You can deallocate a memory using a free() function.
Example:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr=(int *)malloc(sizeof(int));
int a=5;
ptr=&a;
free(ptr);
//now this ptr is known as dangling pointer.
printf(“After deallocating its memory *ptr=%d”,*ptr);
return 0;
}

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

*** Error in „./a.out‟: free( ): invalid pointer : 0x00007ffd808ceae4 ***


Aborted (core dumped)

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 12


Pointer Expressions:
In general, expressions involving pointers has same rules as other expressions.
Pointer Assignments:
We can use a pointer on the right-hand side of an assignment to assign its value to
another pointer.
Example:
/* Simple program illustrating pointer assignment */
#include<stdio.h>
main()
{
int var=50;
int *p1,*p2;
p1=&var;
p2=p1;
printf(“Values at p1 and p2 are : %d %d\n”,*p1,*p2); /* print the value of var twice */
printf(“Address pointed by p1 and p2 are : %p %p”, p1, p2); /* print the address of var twice */
}

Output:
Value at p1 and p2 are: 50 50
Address pointed by p1 and p2 are: 0052FAD0 0052FAD0

After two assignment statements: p1=&var and p1=p1, p1 and p2 both point to variable
var. Thus, both p1and p2 refer to the same object. It is important to note that the addresses are
displayed by using the %p printf( ) format specifier, which causes printf( ) to display an address
in the format used by the host computer.

Pointer Conversions
It is also possible to assign a pointer of one type to a pointer of another type. This is
achieved using pointer conversion. There are two general types of conversion:
 One which involves void * pointer and
 Which do not involves void * pointers.
In C, it is allowed to assign a void * pointer to any other type of pointer. It is also allowed to
assign any other type of pointer to a void * pointer. A void * pointer is called a generic pointer.
Usually, the void * type is used to specify a pointer whose base type is unknown.
Except for void * , all other pointer conversions must be performed by using an explicit
cast. However, the conversion of one type of pointer into another type may create undefined
behavior. This illustrated in the following example:
/* pointer conversion*/
#include<stdio.h>
main( )
{
double x=50.6, y;
int *p;
p=(int *) &x; /* p (which is an integer pointer) points to double */
y=*p; /* wrong attempt to assign y the value of x through p */

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 13


printf(“The (incorrect) value of x is %f”,y);
}
In the above example, an explicit cast is used when assigning address of x (which is
implicitly a double * pointer) to p, which is an int * pointer. Even though, this cast is correct, it
does not cause the program to act as intended. This is because, the p is and integer pointer and it
will transfer only 4 bytes of information to y with the assignment statement y=*p;. The
remaining 4 bytes (recall that double takes 8 bytes) are inaccessible. Thus even though p is a
valid pointer, the fact that it points to double does not change the fact that operations on it except
int values.

Address Arithmetic:
Let us consider why we need to identify the type of variable that a pointer points to, as in:
int *ptr;
One reason for doing this is so that later, once prt points to something, if we write:
*prt=2;
Now 2 is assigned to the address location which is pointed by pointer ptr.
The compiler will know how many bytes to copy into that memory location pointed to by
ptr. If ptr was declared as pointing to an integer, 4 bytes would be copied. Similarly for floats
and doubles the appropriate number will be copied. But defining the type that the pointer points
to allow a number of other interesting ways a compiler can interpret code. For example, consider
a block in memory consisting of ten integers in a row. That is, 40 bytes of memory are set aside
to hold 10 integers.
Now let us say we point our integer pointer, ptr at the first of these integers. Let us
assume that integer is located at memory location 1000 (decimal). What happens when we write
ptr+1;
Because the compiler knows this is a pointer (i.e. its value is an address) and that it points to an
integer (its current address, 1000, is the address of an integer) it adds 4 to ptr instead of 1, so the
pointer “points to” the next integer, at memory location 1004. Similarly, if the ptr was declared
as a pointer to a short, it would add 2 to it instead of 1. The same goes for other data types such
as float, double or even user defined data types such as structures. This is obviously not the same
kind of addition that we normally thing of. In C, it is referred to as addition using pointer
arithmetic.
Similarly, since ++ptr and ptr++ are both equivalent to ptr+1, incrementing a pointer using the
unary ++ operator either pre or post, increments the address it stores by the amount sizeof(type)
where type is the type of object pointed to. (i.e. 4 for an integer).
Example:
/* simple program illustrating pointer arithmetic */
#include<stdio.h>
main( )
{
int *p,num;
p=&num;
*p=100;
printf(“%d\n”,num);
(*p)++;
printf(“%d\n”,num);

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 14


(*p)--;
printf(“%d\n”,num);
}
Output:
100
101
100
Pointer Comparisons:
Pointer variables can be compared provided both variables are of the same data type.
Such comparisons can be useful when both pointer variables point to elements of same array.
The comparisons can test for either equality or inequality. Furthermore, a pointer variable can be
compared with zero (NULL).
The logical expressions that can be used with two pointer variables are as given below:
int *p, *q;
(p<q)
(p>=q)
(p= =q)
(p!=q)
(p= =NULL)
We can compare two pointers in a relational expression. We can use following operators
to compare two pointers.
= =, !=, <, >, <=, >=
For example
if(x<y)
printf(“x points to lower memory that y\n”);
Generally pointer comparisons are useful only when two pointers point to a common
object, such as an array.
Pointers to Pointer:
We can have a pointer to point to another pointer that will point to the target value. This
situation is called multiple indirection, or pointer to pointers. The following example illustrates
this concept:
#include<stdio.h>
main()
{
int n, *p,**q;
n=50;
p=&n;
q=*p;
printf(“%d”,**q); /* print the value of n */
}
Ouput:
50
Here, p is declared as a pointer to an integer and q as a pointer to a pointer to an integer.
As shown in the above example, the value of a normal pointer is the address of the object
that contains the desired value. In the case of the pointer to pointer, the first pointer contains the
address of the second, which points to the object that contains the desired value.

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 15


The following figure differentiating single and multiple indirection.
Pointer Variable
Address Value

Single indirection
Pointer 1 Pointer 2 Variable

Address Address Value

Multiple indirection
Pointer to pointer declaration:
A pointer to pointer variable is declared by placing an additional asterisk in front of the
variable name as shown below:
float **amount;
Here, amount is a pointer to pointer of type float.
It is important to note that amount is not a pointer to a floating-point number but rather a
pointer to a float pointer.

Pointers and Arrays:


We know that array elements are located continuously in memory and array name is
really pointer to the first element in the array. This brings up an interesting relationship between
arrays and pointers. Consider the following example:
int array[ ] = {1, 20, 32, 12, 45, 100, 56, 78};
Here, we have an array containing 8 integers. We refer to each of these integers by means of a
subscript to array, i.e. using array[0] through array[7]. But, we could alternatively access them
via a poiner as follows:
int *ptr;
ptr=&array[0]; or
ptr=a; /* point out pointer at the first integer in our array */
We could print out our array either using the array notation or by dereferencing our
pointer.
Example:
Write a C program to find sum, mean and standard deviation of array elements using pointer.
#include<stdio.h>
#include<math.h>
void main()
{
float a[100],s=0,m,*p,sumstd=0,std;
int i,n;
printf("enter the array size");
scanf("%d",&n);
printf("enter the array elements");
for(i=0;i<n;i++)

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 16


scanf("%f",&a[i]);
p=a;
for(i=0;i<n;i++)
{
s=s+*p;
p++;
}
m=s/n;
p=a;
for(i=0;i<n;i++)
{
sumstd=sumstd+pow((*p-m),2);
p++;
}
std=sqrt(sumstd/n);
printf("sum is %f\n",s);
printf("mean is %f\n",m);
printf("Standard Deviation is %f",std);
}

Passing arguments to function using pointer:


In C program, arguments are passed to functions by value, i.e. only the values of argument
expressions are passed to the called function. Some programming languages allow arguments
passed by reference, which allows the called function to make changes in argument objects. C
allows only call by value, not call by reference. However, if a called function is to change the
value of an object defined in the calling function, it can pass a value which is a pointer to the
object. i.e. address of the object. The called function can then dereference the pointer to access
the object indirectly using its address. We have also seen that C function can return a single
value as the value of the function. However, by indirect access, i.e. pass by reference using
pointers a called function can effectively return several values. Only one value is actually
returned as the value of the function, all other values may be indirectly stored in objects in the
calling function. This use of pointer variables is one of the most common in C.

One of the best things about pointers is that they allow functions to alter variables outside of
their own scope. By passing a pointer to a function you can allow that function to read and
write to the data stored in that variable. Say we want to write a function that swaps the values of
two variables. Without pointers this would be practically impossible, here's how we do it with
pointers:

#include<stdio.h>
void swap(int *,int *);
main()
{
int a,b;
printf("enter two numbers");
scanf("%d%d",&a,&b);

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 17


printf("values before swapping\n");
printf("a=%d\n",a);
printf("b=%d\n",b);
swap(&a,&b);
printf("values after swapping\n");
printf("a=%d\n",a);
printf("b=%d\n",b);

}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
As we can see, the function declaration of swap( ) tells compiler to expect two pointers
(address of variables). Also, the address-of operator (&) is used to pass the address of the two
variables rather than their values. swap( ) then reads address.

Review Questions

1. What is string? How is it declared and initialized? (5 Marks)


2. Explain the functions used to read strings with examples. (5 Marks)
3. Explain the functions used to display string on screen with examples.(5 Marks)
4. List the most commonly used string handling functions and explain their usage. (8
Marks)
5. Explain the character functions in C with examples. (8 Marks)
6. Write a C program to check the given string is palindrome or not. (6 Marks)
7. Write a C program to count the number of vowels and consonants in a given string. (6
Marks)
8. What is pointer? What is its purpose? (4 Marks)
9. How is pointer variable declared in C? (4 Marks)
10. Explain the process of initialization of pointer variable. (4 Marks)
11. Write a short note on operations on pointers. (4 Marks)
12. What do you mean pointer to pointer? Explain. (4 Marks)
13. Write a note on arrays and pointers. (4 Marks)
14. How can a pointer variable be passed to a function? Explain with example. (6 Marks)
15. Explain pointer conversions with examples.(5 Marks)
16. Explain pointer arithmetic with examples. (4 Marks)
17. Write a C program to find sum, mean and standard deviation of array elements using
pointer. (8 Marks)
18. Write a C program to swap two given numbers using call by reference. (6 Marks)

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 18

You might also like