Module-4
Strings and Pointers: Introduction, string
taxonomy, operations on strings, Miscellaneous
string and character functions, arrays of strings.
Pointers: Introduction to pointers, declaring
pointer variables, Types of pointers, Passing
arguments to functions using pointers
❖ In C language, a string is a null-terminated character array. This means that after the last character, a
null character (‘\0’) is stored to signify the end of the character array.
❖ char str[] = “HELLO”;
❖ Declaring a character array that has five usable characters namely, H, E, L, L, O. Apart from these
characters, a null character (‘\0’) is stored at the end of the string.
❖ To store a string of length 5, we need 5+1 locations (1 extra for the null character).
❖ If we declare str as char str[5] = “HELLO”;
❖ Then the null character will not be appended automatically to character array. This is because str can
hold only 5 characters and the characters in HELLO have already filled the locations allocated to it.
• When the compiler assigns a character string to a character array, it automatically appends a
null character to the end of the string. Therefore, the size of the string should be equal to
maximum number of characters in the string plus one.
• When allocating memory space for a character array, reserve space to hold the null character
also.
❖ In the above figure 1000, 1001, 1002, and so on are the memory addresses of individual
characters. As in the figure H is stored at memory location 1000 but in reality the ASCII codes
of characters are stored in memory and not the character itself, i.e., at the address 72 will be
stored since the ASCII code for H is 72.
❖ char str[] = “HELLO”;
❖ The given statement declares a constant string as we have assigned value to it while declaring
the string.
❖ The general form of declaring a string is: char str[size];
❖ When we declare the string in this way, we can store size-1 characters in the array because the
last character would be the null character.
❖ char str[] = { ‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’};
❖ In the above example, we have explicitly added the null character. Further, observe that we
have not mentioned the size of the string. Here, the compiler will automatically calculate the
size based on the number of elements initialized. So, in this example 6 memory slots will be
reserved to store the string variable, str.
❖ We can also declare a string with size much larger than the number of elements that are
initialized.
❖ char str[10] = “HELLO”;
char str[3];
str = “HELLO”;
❖ The above declaration is illegal in C and would generate a compile time error because of two
reasons. First, the array is initialized with more elements than it can store. Second
initialization cannot be separated from declaration.
❖ An array name cannot be used as the left operand of an assignment operator. The following
statement is illegal in C:
char str2, str1[] = “HI”; str2 = str1;
✓ Read String
scanf() to read a string
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output:
Enter name: Dennis Ritchie
Your name is Dennis.
Even though Dennis Ritchie was entered in the above program, only "Dennis" was stored in the name string.
It's because there was a space after Dennis.
Also notice that we have used the code name instead of &name with scanf().
scanf("%s", name);
This is because name is a char array, and we know that array names decay to pointers in C.
Thus, the name in scanf() already points to the address of the first element in the string, which is why we don't
need to use &.
❖ How to read a line of text?
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Output:
Enter name: Tom Hanks
Name: Tom Hanks
❖ Passing Strings to Functions:
Strings can be passed to a function in a similar way as arrays. Learn more about passing arrays to
a function.
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
✓ String Taxonomy
In C, we can store a string either in fixed-length format or in variable-length format as below:
Fixed-length string: When storing a string in a fixed-length format, we have to specify an
appropriate size for the string variable.
Variable-length strings: A better option is to use a variable length format in which the string can
be expanded or contracted to accommodate the elements in it.
To use a variable-length string format we need a technique to indicate the end of elements that are
a part of the string. This can be done either by using length- controlled string or a delimiter.
Length-controlled strings: Here we need to specify the number of characters in the string. This
count is used by string manipulation functions to determine the actual length of the string variable.
Delimited String: In this the string is ended with a delimiter. The delimiter is then used to identify
the end of the string.
Example: In English language every sentence is ended with a full-stop (.). Similarly, in C language
we can use any character such as comma, semicolon, colon, dash, null character, etc. as the
delimiter of a string. Null character is the most commonly used string delimiter in the C language.
• Operation on strings:
Before we learn about the different operations that can be performed on character arrays, we
must understand the way arithmetic operations can be applied to characters.
int i;
char ch = ‘A’; i = ch;
printf(“%d”, i);
// Prints 65, ASCII value of ch is ‘A’
int i;
char ch = ‘A’; i = ch + 10;
printf(“%d”, i);
// Prints 75, ASCII value of ch that is ‘A’ + 10
❖ Finding the Length of a String
The number of characters in the string constitutes the length of the string.
Example: LENGTH (“C Programming is fun”) will return 20. Note that even blank spaces are
counted as characters in the string.
LENGTH (“\0”) =0 and LENGTH(“ “) = 0 because both the string do not contain any character.
Therefore, both the strings are empty and of zero length.
• Write a program to find the length of string:
#include <stdio.h>
int main()
{
char str[100], i = 0, length;
printf(" \n Enter the String:"); gets(str);
while(str[i]!='\0') i++;
length = i;
printf("\n The length of the string is: %d", length); return 0;
}
Output:
Enter the String: HELLO
The length of the string is: 5
• Converting Characters of a String into Upper Case
As we already know that in memory the ASCII codes are stored instead of all real value. The
ASCII code for A-Z varies from 65-91 and ASCII code for a-z ranges from 97-123.
So, if we have to convert a lower case letter to upper case letter, then we just need to subtract 32
from the ASCII value of the character.
• Write a program to convert characters of a string to upper case.
#include <stdio.h>
int main()
{
char str[100], upper_str[100]; int i = 0, j=0;
printf(" \n Enter the String:");
gets(str); while(str[i]!='\0')
{
if(str[i]>='a' && str[i]<='z') upper_str[j] = str[i]-32; else
upper_str[j] = str[i]; i++;
j++;
}
upper_str[j] = '\0';
printf("\n The string converted into upper case is:"); puts(upper_str);
return 0;
}
Output:
Enter the String: hello
The string converted into upper case is: HELLO
• Concatenating Two strings to Form a New String:
If S1 and S2 are two strings, then concatenation operation produces a string which contains characters of S1
followed by the Characters of S2.
• Write a program to concatenate two strings.
#include <stdio.h>
int main()
{
char str1[100],str2[100], str3[100]; int i = 0, j=0;
printf(" \n Enter the first String:");
gets(str1);
printf(" \n Enter the second String:"); gets(str2);
while(str1[i]!='\0')
{
str3[j] = str1[i]; i++;
j++;
}
i = 0;
while(str2[i]!='\0')
{
str3[j] = str2[i]; i++;
j++;
}
str3[j] = '\0';
printf("\n The concatenated string is:"); puts(str3);
return 0;
}
Output:
Enter the first String: JSS Enter the second String: ATEB
The concatenated string is: JSSATEB
• Appending a String to Another String:
Appending one string to another string involves copying the contents of the source string at the end of the
destination string.
Example: If S1 and S2 are two strings, then appending S1 to S2 means we have to add the contents of S1 to
S2. Here S1 is the source and S2 is the destination string.
S2 = S2 + S1
Write a program to append a string to another string:
#include <stdio.h>
int main()
{
char Dest_Str[100],Source_Str[50]; int i=0, j=0;
printf("\n Enter the source string:");
gets(Source_Str);
printf("\n Enter the destination string:"); gets(Dest_Str);
while(Dest_Str[i] != '\0')
i++;
while(Source_Str[j] !='\0')
{
Dest_Str[i] = Source_Str[j]; i++;
j++;
}
Dest_Str[i] = '\0';
printf("\n After appending, the destination string is:"); puts(Dest_Str);
return 0;
}
Output:
Enter the source string: JSSATE
Enter the destination string: Bengaluru
After appending, the destination string is: BengaluruJSSATE
• Write a program to compare two strings:
#include <stdio.h> #include<string.h>
int main()
{
char str1[50], str2[50];
int i=0, len1=0, len2=0, same=0;
printf("\n Enter the first string:"); gets(str1);
printf("\n Enter the second string:");
gets(str2);
len1 = strlen(str1);
len2 = strlen(str2); if(len1==len2)
{
while(i<len1)
{
if(str1[i] == str2[i]) i++;
else break;
}
if(i==len1)
{
same=1;
printf("\n The two strings are equal");
}
if(len1!=len2)
printf("\n The two strings are not equal"); if(same==0)
{
if(str1[i]>str2[i])
printf("\n String1 is greater than dtring2"); else if(str1[i]<str2[i])
printf("\n String2 is greater than string1");
}
}
return 0;
}
Output:
Enter the first string: Hello Enter the second string: Hello The two strings are equal
• Reversing a String:
If S1 = “HELLO”, then reverse of S1 = “OLLEH”. To reverse a string we just need to swap the first character
with the last, second character with the second last character, so on and so forth.
#include <stdio.h>
#include<string.h>
int main()
{
char str[100], reverse_str[100],temp; int i=0, j=0;
printf("\n Enter the string"); gets(str);
j = strlen(str)-1; while(i<j)
{
temp = str[j]; str[j] = str[i];
Str[i]=temp
i++; j++;
}
printf("\n The reverse string is:"); puts(str);
return 0;
}
Output:
Enter the string: HELLO
The reverse string is: OLLEH
• Inserting a String in Another String:
The insertion operation inserts a string S in the main text T at Kth position. The general syntax of this
operation is: INSERT(text, position, string).
Example: INSERT(“XYZXYZ”, 3, “AAA”) = XYZAAAXYZ
#include <stdio.h>
#include<string.h>
int main()
{
char text[100], str[100], ins_text[100]; int i=0, j=0, k=0, pos;
printf("\n Enter the main text:");
gets(text);
printf(" Enter the string to be inserted:"); gets(str);
printf("\n Enter the position at which the string has to be inserted:");
scanf("%d", &pos);
while(text[i]!='\0')
{
if(i==pos)
{
while(str[k]!='\0')
{
ins_text[j]=str[k]; j++;
k++;
}
}
else
{
ins_text[j]=text[i]; j++;
}
i++;
}
ins_text[j]='\0';
printf("\n The new string is:"); puts(ins_text);
return 0;
}
Output:
Enter the main text: How You ? Enter the string to be inserted: Are
Enter the position at which the string has to be inserted: 3 The new string is: How Are You?
• Miscellaneous String and Character Functions:
Character and string manipulation functions that are part of header files ctype.h, string.h, stdlib.h.
13.5.1 Character Manipulation Functions : Below table illustrates some character functions contained
in ctype.h
• String Manipulation Functions:
• strcat Function:
Syntax:
char *strcat(char *str1, const char *str2);
The strcat function appends the string pointed to by str2 to the end of the string pointed to by str1.
The terminating null character of str1 is overwritten. The process stops when the terminating null
character of str2 is copied. The argument str1 is returned.
Note: the str1 should be big enough to store the content of str2.
#include <stdio.h>
#include<string.h>
int main()
{
char str1[50] = "Programming"; char str2[] = " In C";
strcat(str1, str2); printf("\n str1: %s", str1);
return 0;
}
Output:
str1: Programming In C
• strncat Function:
Syntax:
char *strncat(char *str1, const char *str2, size_t n);
The function appends the string pointed to by str2 to the end of the string pointed to by str1 up to n characters
long.
The terminating null character of str1 is overwritten.
Copying stops when n characters are copied or the terminating null character of str2 is copied.
A terminating null character is appended to str1 before returning to the calling function.
#include <stdio.h>
#include<string.h>
int main()
{
char str1[50] = "Programming "; char str2[] = "In C";
strncat(str1, str2, 2); printf("\n str1: %s", str1);
return 0;
}
Output:
str1: Programming In
• strchr Function:
Syntax:
char *strchr(const char *str, int c);
The strchr() function searches for the first occurrence of the character c ( an unsinged char) in the string
pointed to by the argument str. The function returns a pointer pointing to the first matching character, or
NULL if no match is found.
#include <stdio.h> #include<string.h> int main()
{
char str[50] = "Programming In C"; char *pos;
pos = strchr(str,'n'); if(pos)
printf("\n n is found in str at position %d", pos); else
printf("\n n is not present in the string"); return 0;
}
Output:
n is found in str at position 9
• strrchr Function:
Syntax:
char *strrchr(const char *str, int c);
The strrchr() function searches for the first occurrence of the character c(an unsinged char) beginning at
the rear end and working towards the front in the string pointed to by the argument str, i.e., The function
searches for the last occurrence of the character C and returns a pointer pointing to the last matching
character, or NULL if no match is found.
#include <stdio.h>
#include<string.h>
int main()
{
char str[50] = "Programming In C"; char *pos;
pos = strrchr(str,'n'); if(pos)
printf("\n The last position of n is: %d", pos); else
printf("\n n is not present in the string"); return 0;
}
Output:
The last position of n is: 13
• strcmp Function:
syntax:
int strcmp(const char *str1, const char *str2);
The strcmp function compares the string pointed to by str1 to the string pointed to by str2. The function
returns zero if the string are equal. Otherwise, it returns a value less than zero or greater than zero if str1
is less than or greater than str2 respectively.
#include <stdio.h>
#include<string.h>
int main()
{
char str1[10] = "HELLO" ; char str2[10] = "HEY"; if(strcmp(str1,str2)==0)
printf("\n Two strings are identical");
else
printf("\n The two strings are not identical"); return 0;
}
Output:
The two strings are not identical
• strncmp Function:
Syntax:
int strncmp(const char *str1, const char *str2, size_t n);
This function compares at most the first n bytes of str1 and str2. The process stops comparing after the null
character is encountered. The function returns zero if the first n bytes of the string are equal. Otherwise, it
returns a value less than zero or greater than zero if str1 is less than or greater than str2, respectively.
#include <stdio.h>
#include<string.h>
int main()
{
char str1[10] = "HELLO" ; char str2[10] = "HEY"; if(strncmp(str1,str2,2)==0)
printf("\n Two strings are identical");
else
printf("\n The two strings are not identical"); return 0;
}
Output:
Two strings are identical
• strcpy Function:
Syntax: char *strcpy(char *str1, const char *str2);
This function copies the string pointed to by str2 to str1 including the null character of str2. It returns the
argument str1. Here str1 should be big enough to store the contents of str2.
include <stdio.h>
#include<string.h>
int main()
{
char str1[10], str2[10] = "HELLO" ; strcpy(str1,str2);
printf("\n str1: %s", str1);
return 0;
}
Output:
str1: HELLO
• strlen Function:
Synatx: size_t strlen(const char *str);
This function calculates the length of the string str up to but not including the null character, i.e., the
function returns the number of characters in the string.
#include <stdio.h>
#include<string.h>
int main()
{
char str[] = "HELLO" ;
printf("\n Length of str is: %d", strlen(str)); return 0;
}
Output: Length of str is: 5
• atoi() Function:
As we know that the value 1 is an integer and ‘1’ is a character. So there is a huge difference when we
write the two statements given below.
int i=1; // here i=1
int i=‘1’; // here i = 49, the ASCII value of character 1
Similarly, 123 is an integer number but ‘123’ is a string of digits. What if you want to operate some integer
operations on the string ‘123’? For this, C provides a function atoi that converts a given string into its
corresponding integer.
int atoi (const char *str); Example: i=atoi(“123.456”); Result: i = 123.
• atof() Function:
The atof() function converts the string that it accepts as an argument into a double value and then returns
that value to the calling function.
Syntax:
double atof(const char *str);
Example: x = atof(“12.39 is the answer”); Result: x = 12.39
• atol() Function:
•
The atol() function converts the string into a long int value. The atol function returns the converted long
value to the calling function. Like atoi, the atlo() function will read from a string until it finds any
character that should not be in a long.
Syntax: long atoll(const char *str); Example: x=atol(“12345.6789”);
Result: x=12345L.
✓ Arrays of Strings:
❖ If there are 20 students in a class and we need a string that stores names of all the 20 students.
❖ Here, we need a string of strings or an array of strings. Such an array of strings would store 20
individual strings. An array of strings is declared as:
char names[20][30];
❖ Here, the first index that specifies the number of strings that are needed and the second index
specifies the length of every individual string. So here, we allocate space for 20 names where each
name can be a maximum of 30 characters long.
❖
<data_type> <array_name> = { “Ram”, “Mohan”, “Shyam”, “Hari”, “Gopal”};
Write a program to read and print the names of n students of a class:
#include <stdio.h>
int main()
{
char names[5][10]; int i,n;
printf("\n Enter the number of students:");
scanf("%d",&n); for(i=0;i<n;i++)
{
printf("\n Enter the name of student %d:", i+1); gets(names[i]);
}
printf("\n Names of the student are: \n"); for(i=0;i<n;i++)
puts(names[i]); return 0;
}
Output:
Enter the number of students: 2
Enter the name of student 1: ABC
Enter the name of student 2: XYZ
Names of student are: ABC XYZ
Pointers:
✓ Understanding the Computer’s Memory
❖ Every computer has a primary memory. All data and programs need to be placed in the
primary memory for the execution.
❖ RAM is a part of the primary memory, is a collection of memory locations and each location
has a specific address.
❖ Each memory location is capable of storing 1byte of data.
❖ Ex: char type data needs just 1 memory location and int type data needs 2 memory locations.
❖ In general, the computer has three areas of memory each of which is used for a specific task.
These areas of memory includes : stack, heap, and global memory.
❖ Stack: A fixed size of memory called system stack is allocated by the system and is filled as
needed from the bottom to the top, one element at a time.
❖ These elements can be removed from the top to the bottom by removing one element at a
time, i.e., the last element added to the stack is removed first.
❖ Heap: It is a contiguous block of memory that is available for use by programs when the
need arises. A fixed size heap is allocated by the system and is used by the system in a
random fashion.
The addresses of the memory locations in heap that are not currently allocated to any program for
use are stored in a free list. When a program requests a block of memory the dynamic allocation
technique takes a block from the heap and assigns it to the program.
❖ Global Memory: The block of code that is the main() program is stored in the global
memory.
❖ The memory in the global area is allocated randomly to store the code of different functions
in the program in such a way that one function is not contiguous to another function.
❖ Beside the function code, all global variables declared in the program are stored in the global
memory area.
❖
✓ Introduction to Pointers:
❖ Every variable in C has a name and a value associated with it. When a variable is
declared, a specific block of memory within the computer is allocated to hold the value
of that variable.
❖ The size of the allocated block depends on the type of the data.
❖ The size of integer may vary from one system to another. In 32 bit systems, integer
variable is allocated 4 bytes while on 16 bit systems it is allocated 2 bytes.
Write a program to find the size of various data types on your system.
#include<stdio.h>
int main()
{
printf("\n The size of short integer is:%d", sizeof(short int));
printf("\n The size of unsigned integer is %d", sizeof(unsigned int));
printf("\n The size of signed integer is %d", sizeof(signed int)); printf("\n The size of integer is %d",
sizeof(int));
printf("\n The size of long integer is %d", sizeof(long int));
printf("\n The size of character is %d", sizeof(char));
printf("\n The size of unsigned character is %d", sizeof(unsigned char));
printf("\n The size of signed charactet is %d", sizeof(signed char));
printf("\n The size of floating point number is %d", sizeof(float));
printf("\n The size of idouble is %d", sizeof(double)); return 0;
}
Output:
The size of short integer is:2
The size of unsigned integer is 4
The size of signed integer is 4
The size of integer is 4
The size of long integer is 8
The size of character is 1
The size of unsigned character is 1
The size of signed character is 1
❖ The size of floating point number is 4
❖ The size of double is 8
❖ Pointer: Is nothing but memory addresses. A pointer is a variable that contains the memory location
of another variable.
❖ Therefore a pointer is a variable that represents the location of a data item, such as a variable or any
array element.
✓ Applications:
❖ To pass information back and forth between a function and its reference point.
❖ Enable programmers to return multiple data items from a function via function arguments.
❖ Provide an alternate way to access individual elements of the array.
❖ To pass arrays and strings as function arguments.
❖ Enable references to functions. So with pointers, programmers can even pass function as argument to
another function.
❖ To create complex data structures such as tress, linked lists, linked stacks, linked queues, and graphs.
❖ For dynamic memory allocation of a variable.
Declaring Pointer Variables: A pointer provides access to a variable by using the address of that variable. A
pointer variable is therefore a variable that stores the address of another variable.
Syntax of declaring pointer variable: data_type *ptr_name;
Here, data_type is the data type of the value that the pointer will point to. int *pnum;
char *pch; float *pfnum;
#include<stdio.h>
int main()
{
int *pnum; char *pch;
float *pfnum;
double *pdnum; long *plnum;
printf("\n Size of integer pointer = %d", sizeof(pnum));
printf("\n Size of character pointer = %d", sizeof(pch));
printf("\n Size of float pointer = %d", sizeof(pfnum));
printf("\n Size of double pointer = %d", sizeof(pdnum));
printf("\n Size of long pointer = %d", sizeof(plnum));
return 0;
}
❖ Declare an integer pointer variable and start using it in the program.
❖ int x =10;
❖ int *ptr;
❖ ptr = &x;
❖ In the above ptr is the name of pointer variable. The ‘*’ informs the compiler that ptr is a pointer variable
and the int specifies that it will store the address of an integer variable.
❖ An integer pointer variable, therefore, points to an integer variable. Here ptr is assigned the address of x.
The & operator retrieves the lvalue (address) of x, and assigns it to the pointer ptr.
Since X is an integer variable, it will be allocated 2 bytes. Assuming that the compiler assigns it memory
locations 1003 and 1004, we say the value of x = 10 and the address of x (written as &x) is equal to
1003, i.e., the starting address of x in the memory.
We write, ptr = &x, the ptr = 1003
We can dereference a pointer, i.e., refer to the value of the variable to which it points, by using unary ‘*’
operator (also known as indirection operator) as *ptr, i.e.,
*ptr = 10, since 10 is value of x. Therefore, * is equivalent to writing value at address.
#include<stdio.h>
int main()
{
int num, *pnum;
pnum = #
printf("\n Enter the number"); scanf("%d", &num);
printf("\n The number that was entered is: %d", *pnum);
printf("\n The address of number in memory is: %p", &num); return 0;
}
Output:
Enter the number10
The number that was entered is: 10
The address of number in memory is: 0x7fff9f61bd44
❖ Note: what will be the value of *(&num) ? Yes it is equivalent to num. The indirection and the
address operators are inverse of each other, so when combined in an expression, they cancel each
other.
❖ We can also assign values to variables using pointer variables and modify their values.
#include<stdio.h>
int main()
{
int num, *pnum; pnum = #
*pnum = 10;
printf("\n *pnum = %d", *pnum); printf("\n num = %d", num);
*pnum = *pnum + 1;
printf("\n After increment *pnum =%d", *pnum);
printf("\n After increment num = %d", num); return 0;
}
Output:
*pnum = 10
num = 10
After increment *pnum =11
After increment num = 11
✓ Null Pointer:
Pointer variable is a pointer to some other variable of the same data type. However in some special cases we
may prefer to have null pointer which is a special pointer that does not point to any value.
Null pointer does not point to any valid memory address.
To declare a null pointer you may use the predefined constant NULL, which is defined in several
standard header files including <stdio.h>, <stdlib.h>, and
<string.h>.
After including any of these header files in the program: int *ptr = NULL;
We may also initialize a pointer as a null pointer by using a constant 0, as below:
if(ptr == NULL)
{
Statement Block;
}
❖ We can also initialize a pointer as a null pointer by using a constant 0 as shown below:
❖ int ptr;
❖ ptr = 0;
❖ This is a valid statement in C, as NULL which is a preprocessor macro typically has the value, or
replacement text 0. however, to avoid ambiguity it is always better to use NULL to declare a null pointer.
❖ A function that returns pointer values can return a null pointer when it is unable to perform its task.
❖ Null pointers are used in situation where one of the pointer in the program points to different locations at
different times.
✓ Generic Pointer:
❖ A generic pointer is a pointer variable that has void as its data type.
❖ The void pointer, or the generic pointer, is a special type of pointer that can be used to point to
variables of any data type.
❖ It is declared like a normal pointer variable but using the void keyword as the pointer’s data type.
❖ void *ptr;
❖ In C, since we cannot have a variable of type void, the void pointer will therefore not point to
any data and thus cannot be dereferenced.
❖ We need to type cast a void pointer (generic pointer) to another kind of pointer before using
it.
❖ Generic pointer are often used when we want a pointer to point to data of different types at
different times.
#include<stdio.h>
int main()
{
int x =10;
char ch = 'A'; void *gp;
gp = &x;
printf("\n Generic pointer points to the integer value = %d", *(int*)gp); gp =&ch;
printf("\n Generic pointer now points to the charcater = %c", *(char*)gp);
return 0;
}
Output:
Generic pointer points to the integer value = 10 Generic pointer now points to the character = A
✓ Passing Arguments to function using Pointers:
❖ Call-by-value: passing parameters to a function. In this approach it is impossible to modify the actual
parameters when we pass them to a function.
❖ The incoming arguments to a functions are treated as local variables in the function and those local
variables get a copy of the values passed from their calling function.
❖ Pointers provides a mechanism to modify data declared in one function using code written in another
function.
❖ If data is declared in func1() and we want to write code in func2() that modifies the data in func1(),
then we must pass the address of the variables to func2().
❖ The calling function sends the addresses of the variables and the called function declares those
incoming arguments as pointers. In order to modify the variables sent by the calling function, the
called function must dereference the pointers that were passed to it.
❖ Thus, passing pointers to a function avoids the overhead of copying data from one function to
another. Hence, to use pointers for passing arguments to a function, the programmer must do the
following:
❖ Declare the function parameters as pointers
❖ Use the dereferenced pointers in the function body
❖ Pass the addresses as the actual argument when the function is called.
Write a program to add two integers using functions:
#include<stdio.h>
void sum(int *a, int *b, int *t);
int main()
{
int num1, num2, total;
printf("\n Enter the first number:"); scanf("%d", &num1);
printf("\n Enter the second number:");
scanf("%d", &num2); sum(&num1, &num2, &total); printf("\n Total = %d", total); return 0;
}
void sum(int *a, int *b, int *t)
{
*t = *a + *b;
}
Output:
Enter the first number: 2
Enter the second number: 3
Total = 5