C - Pointers and Strings

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Jyoti Chandnani

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;

Syntax : int *ptr;


ptr= & i; // it can hold the address of i.
3000 → pointer variable address
2000
Ptr
I = 10
Ptr= 2000
*ptr = 10
&ptr = 3000

& → address operator returns the address of the variable.


%u or %lu → format specifier to display address
* → pointer operator which displays value at address.

Example :
// demo for pointer variable

#include<stdio.h>
void main()
{
int i=10;
int *ptr;
ptr=&i;

printf("value of %d ",i); // value of the variable - 10


printf("\naddress of i %u",&i); // address of I - 2000
printf("\naddress of i %u",ptr); // value of the variable 2000
Jyoti Chandnani

printf("\nvalue of i %d",*ptr); // value of I - 10


printf("\naddress of ptr %u",&ptr); // address of ptr- 3000
}

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.

Eg: int x=10


2000 → Address
10(value)
x → variable name

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

Null Pointer Assignment

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

Passing Pointers to function


Two types :
1. Pass by value
2. Pass by reference

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.

Call by reference: When a pointer is passed as argument to a function, the address of


actual arguments is passed. That why changes made to formal argument directly
reflect the actual arguments. Using call by reference function can return more than
one value at a time.

Example on call by value and call by reference:


Jyoti Chandnani

// WAF to swap the given values to the function.


// call by value & call by reference
void Swap(int,int);
void Swapref(int *, int *);
#include<stdio.h>
void main()
{
int a,b,temp;

printf("Enter first number ");


scanf("%d",&a);

printf("Enter second number");


scanf("%d",&b);

//printf("\n Call By Value");


Swap(a,b);

printf("\n Call By reference");


Swapref(&a,&b);
printf("\n\n(main) Values for a and b are %d and %d",a,b);
printf("\n\n\n\n");
}

void Swap(int x, int y) // formal parameters


{
int temp;
temp=x;
x=y;
y=temp;
printf("\n\nValues after swapping of a and and b = %d and %d :\n\n\n\n\n ",x,y);
}

//function for call by reference


void Swapref(int *x, int *y) // formal parameters
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Jyoti Chandnani

Array and pointers

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)

Pointer can point to the first address of an array


ptr=&arr[0];
ptr=arr;
arr1[1]=*ptr;

int arr[5] =
Base address
Arr arr+1 arr+2 arr+3 arr+4
65502 65506 65510 65514 65518
Ptr ptr++ ptr++

Example : Program to access array elements of a one dimensional array using


pointers.
#include<stdio.h>
void main()
{
int arr[5]={10,20,30,40,50};
int *ptr;
ptr=arr;
int i;
printf("Using array as pointer\n");
for(i=0;i<5;i++)
{
printf("%d = %d\n",arr[i],*(arr+i));
}
printf("\n\nUsing Pointer ");
for(i=0;i<5;i++)
{
printf("%d ",*ptr++);
}
printf("\n\n\n\n"); }
Jyoti Chandnani

Pointers and two-dimensional arrays

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];

Rather than int arr[3][5];

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

Dynamic Memory allocation


An array is a collection of items stored at contiguous memory location with fixed size.

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.

C provides some functions to achieve this


Malloc()
Free()
Reallocate()

The “malloc” or “memory allocation” method in C is used to dynamically allocate a


block of memory with the specified size. It doesn’t Initialize memory at execution
time so the default garbage value is allocated initially.

Syntax : ptr = (data_type*) malloc(byte-size)

ptr = (int*) malloc(5 * sizeof(int)); = int *ptr[5];

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;

// Get the number of elements for the array


printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);

ptr = (int*)malloc(n * sizeof(int));


if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0); // exit from the program
}
else {
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

printf("The elements of the array are: ");


for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
free(ptr); // deallocate the memory
return 0;
}
Jyoti Chandnani

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);

for (i = 0; i <= index; i++) {


printf("marks of students %d are: %d\n ", i,marks[i]);
}
free(marks);
}
return 0;
}
Jyoti Chandnani

Strings
Group of characters, digits or symbols enclosed in double quotes or simple we can
say string is declared as “character array”.

Declaration and Initialisation of Strings

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.

Syntax : char_type string_name [size] ;

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.

//Program to demonstrate strings


#include<stdio.h>
Void main()
{
char name[];
Printf(“Enter you Name “);
Scanf(“%s”,name); // base address of an array
Printf(“Name = %s”,name);
}

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

gets() and puts() function


scanf() and gets() can accept only one string at a time and printf() and puts() will
display only one string at a time. But advantage of using gets is it can accept multi
words string.

# include
int main( )
{
char name[ 25 ] ;
printf ( "Enter your full name: " ) ;
gets ( name ) ;
puts ( "Hello!" ) ;
puts ( name ) ;
return 0 ;
}
Jyoti Chandnani

Displaying strings on various formatting techniques

%s format specifier is used to display the strings. For eg:


printf(“%s”,name);

If you want to display first 5 characters from the field of 15 :


Printf(“%15.5”,name);

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];

First [ ] – is for number of strings we are going to store


Second [ ]- length of each string

Example char name[3][10]={“Jyoti”,”Jiya”,”Jyot”};

Example : Write a program to read and display 3 strings.

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

Pointers and Strings


We can form an array of strings, referred to as a string array. Each element in an
array is string, but in C a string is essentially a pointer to its first character, so each
entry in an array of strings is actually a pointer to the first character of a string.
Consider the following eg:
Char *country[5] = { “India”,”Pakistan”,”China”,”USA”,”UAE”};

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

The *country[] indicates an array of 5 strings


Char* indicates each element of array element is pointer to char
Thus country[0] = “India”
Country[1] = “Pakistan”
And so on…
Jyoti Chandnani

Example 1: passing character pointer to function

#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));

printf(“enter five countries \n);


getcountry(country,5);
displaycountry(country,5);
}

void getcountry( char * country[],int n)


{
int i;
for(i=0;i<n;i++)
scanf(“%s”,country[i]);
return;
}

void displaycountry(char *country[],int n)


{ int i;
for(i=0;i<n;i++)
printf(“%s ”,country[i]);
return;
}
Jyoti Chandnani

Built In string functions and Application


The header file string.h contains some string manipulation functions. Lets check
some of them

1. Strlen () : returns length of the string Syntax : n=strlen(str)

2. Strcpy () : copy one string to another Syntax : strcpy(str1,str2)

3. Strcmp (): Compare two strings n=strcmp(str1,str2) n is the returned value of

differed characters.

4. Strcat () : joins one string to another Syntax strcat(str1,str2)

5. Strncat () : joins one string upto specified no of characters Syntax

strcat(str1,str2,10)

6. Strlwr () : converts upper case characters to lowercase Syntax :strlwr(str)

7. Strupr () : converts lower case characters to upper case Syntax :strupr(str)

8. Strrev(): reverses the given strying Syntax : strrev(str)

9. Strspn(): returns position of the string Syntax : n=strspn(first,second)


Jyoti Chandnani

You might also like