C - Pointers and Strings
C - Pointers and Strings
C - Pointers and Strings
Pointers
A normal variable is a location in memory that can hold a value. For eg. when you
declare a variable i as an integer, four bytes of memory is allocated. 4bytes can store
one integer value.
int i=10;
2000 → Address
10(value)
I → variable name
Pointer is a variable that holds the address of another variable, it doesn’t hold the
value.
It points to another variable by holding its address.
Lets C how to declare pointer variable;
Example :
// demo for pointer variable
#include<stdio.h>
void main()
{
int i=10;
int *ptr;
ptr=&i;
Pointer to Pointer
A pointer can contain address of another pointer. And this pointer variable itself can
be another pointer. This means that a pointer can contain address of another
pointer, which is called Pointer to Pointer.
char *ptr ;
ptr= &x;
3000 → pointer variable address
2000
ptr
int **P=&ptr;
4000 → Address
3000
P → variable name
Example :
I=10
*p1 = &i
**p2= &p1
I= %d - value of I = 10
%u, pi - address of I – 2000
*Ptr - 10
&P - 4000
&ptr – 3000
*(&i) – 10
*ptr +10
Jyoti Chandnani
It doesn’t make any sense to store any value to pointer variable but can assign 0 ,
which can be sometimes used to indicate some specific condition.
Example :
int *pi=NULL;
Printf(“%u is the value of pi”,pi);
Pointer Arithmetic
Pointer variables can also be used in arithmetic expressions. Following operations
can be carried out on pointers:
1. Pointers can be incremented or decremented to point to different locations.
2. If ptr1 and ptr2 are properly declared and initialized pointers, the following
operations are valid:
- Res = res +*ptr1;
- *ptr1 = *ptr2 + 10;
- mul = *ptr1 * *ptr2 ;
3. Expressions like ptr1==ptr2, ptr1<ptr2 etc are valid provided the pointers ptr1
and ptr2 refer to same and related variables.
4. Pointer variables cannot be added eg: c=p1+p2
Call by value : when arguments are passed a copy of values of actual arguments is
passed to the calling function. Thus any changes made to formal arguments will not
affect the actual arguments.
Pointers and arrays are closely related. An array declaration such as int arr[5] will
lead to compiler to pick an address and store 5 integers in contiguous locations and
arr is a name for that address. Array name is the name of that address from where
the sequence of integers starts.
If arr is an array, then the address of first element can be written as &arr[0] or arr
and address of second element can be written as &arr[1] or (arr+1)
So if we use for loop it can be written as
&arr[i] or (arr+i)
int arr[5] =
Base address
Arr arr+1 arr+2 arr+3 arr+4
65502 65506 65510 65514 65518
Ptr ptr++ ptr++
Array of Pointers
The way there are array of integers and array of float , similarly there can be array of
pointers as well. Since a pointer contains an address, an array of pointers would be a
collection of addresses. For eg: two dimensional array can be declared as :
int *arr[3];
As we know array name is a pointer to the first element within the array . so arr
points to the first 3 element array, which is actually first row(i.e row 0) of two
dimensional array. Similarly, (arr+1) points to the second 3 elements array i.e. row 1
and so on.
Arr[i][j] = ((arr+i)+j) - where i = rows and j = cols
Row 1 Arr (Arr+0)+1 Arr+2
Row 2 Arr+1 (Arr+1)+1 (Arr+1)+2
Row 3 Arr+2 (Arr+2)+1 (Arr+2)+2
Example :
void array_of_pointers()
{
int *ptr[Rows];
int rows , cols,i,j;
printf("\nEnter rows and cols \n");
scanf("%d%d",&rows,&cols); 2 4
for(i=0;i<rows;i++)
{ ptr[i]= (int *) malloc (cols*sizeof(int)); } // allocate the memory
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{ scanf("%d",(*(ptr+i)+j)); }
}
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{ printf("%d ",*(*(ptr+i)+j)); }
}
}
Jyoti Chandnani
For eg : int arr[20] and we store only 10 values in an array other 10 will be wasted,
since we cant change the size of an array.
Or another situation can be , if more than 20 values are needed to input then also it
cant be achieved with array as the size is fixed.
But C provides Dynamic Memory Allocation through which size of an array can be
changed at the run time.
this will allocate 4*5 = 20bytes since the integer allocate 4 bytes
ptr will hold the address of first byte in the allocated memory.
Jyoti Chandnani
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
free() method
It is used to de-allocate the memory. The memory allocated using functions
malloc() is not de-allocated on their own. Hence the free() method is used,
whenever the dynamic memory allocation takes place. It helps to reduce wastage
of memory by freeing it.
Syntax: free(ptr);
Realloc() function
Jyoti Chandnani
#include <stdio.h>
#include <stdlib.h>
int main()
{
int index = 0, i = 0, n,*marks;
int ans;
marks = (int*)malloc(sizeof(int));
if (marks == NULL) {
printf("memory cannot be allocated");
}
else {
do {
printf("\n Enter Marks\n");
scanf("%d", &marks[index]); // Get the marks
printf("would you like to add more(1/0): ");
scanf("%d", &ans);
if (ans == 1) {
index++;
marks = (int*)realloc(marks,(index + 1)* sizeof(int));
if (marks == NULL) {
printf("memory cannot be allocated");
}
else {
printf( "\n base address of marks are:%pc",marks);
}
}
} while (ans == 1);
Strings
Group of characters, digits or symbols enclosed in double quotes or simple we can
say string is declared as “character array”.
All strings are ends with special character ‘\0’ Null character. Character requires one
byte to store one character while string requires 2 bytes to store one character eg:
“A\0”.
Declaration
To declare strings character datatype is used.
Eg : char name[20];
Char address [25];
Initialization :
The strings can be initialised as follows:
char name[8]={‘P’,’R’,’O’,’G’,’R’,’A’,’M’,’\0’};
Each character of string occupies 1 byte which is machine dependent. The characters
of strings are stored in contiguous memory locations.
1byte 1byte 1byte 1byte 1byte 1byte 1byte 1byte
P R O G R A M \0
1001 1002 1003 1004 1005 1006 1007 1008
The compiler inserts the Null (\0) character automatically at the end of the string. So
initialisation of null character is not essential but always it occupies 1 extra byte.
String Constants
String constants have double quote marks around them, and can be assigned to char
array or pointers. With character array always give one extra space for Null character
which is a string terminator else it would be considered as character constant.
Eg: 1
{
char *S;
S=”hello”;
printf(“%s\n”,s);
}
Jyoti Chandnani
Eg: 2
{
char s[100];
strcpy(s,”hello”);
Printf(“%s\n”,s);
}
The output of the above code will be same but behaviour of both programs will be
different.
Note :
1.The length of the string should not exceed the size of the character array. This is
because the C compiler doesn’t perform bounds checking on character arrays.
Hence, if you carelessly exceed the bounds, there is always a danger of overwriting
something important
2. scanf( ) is not capable of receiving multi-word strings. Therefore, names such as
“Jyoti Kundnani” would be unacceptable. The way to get around this limitation is by
using the function gets().
Jyoti Chandnani
# include
int main( )
{
char name[ 25 ] ;
printf ( "Enter your full name: " ) ;
gets ( name ) ;
puts ( "Hello!" ) ;
puts ( name ) ;
return 0 ;
}
Jyoti Chandnani
If you include – sign (%10.5s) the string will be printed left justified.
Example1:
Write a program to display following output.
S
St
Stri
Strin
String
Strin
Stri
Str
St
S
Ans:
void format_string()
{
char name1[25];
int i,len;
printf ( "Formatted String " ) ;
gets(name1);
i=5;
len=strlen(name1);
for(i=0;i<=len;i++)
printf("%0.*s\n",i,name1);
for(i=len;i>=0;i--)
printf("%0.*s\n",i,name1);
}
Jyoti Chandnani
Array of Strings :
Array of strings are multiple strings, stored in the form of table. Declaring array of
strings is same as strings, except it will have additional dimension to store the
number of strings
Syntax : char array_name[5][10];
void array_string()
{
char names[5][ 25 ] ;
printf ( "Formatted String " ) ;
for(int i=0;i<3;i++)
scanf("%s",names[i]);
for(int i=0;i<3;i++)
printf("%15.5s\n",names[i]); // 5 characters from the field of 15
}
Jyoti Chandnani
Memory representation
Row →Col 0 1 2 3 4 5 6 7 8
Country[0] I N D I A \0
Country[1] P A K I S T A N \0
Country[2] C H I N A \0
Country[3] U S A \0
Country[4] U A E \0
#include<stdio.h>
void main()
{
char *country[5] ;
int i;
void getcountry(char *[],int);
void displaycountry(char *[],int);
for(i=0;i<5;i++)
country[i]=(char *) malloc(15*sizeof(char));
differed characters.
strcat(str1,str2,10)