Unit 3
Unit 3
Unit 3
ARRAYS
Array of Pointers - Multidimensional Arrays - Pointers and
Strings - Standard string library functions:strlen(), strcpy(),
strcat(),strstr() and strcmp(). Dynamic Memory Allocation
and Deallocation.
INTRODUCTION
• An array is a collection of similar data elements.
• These data elements have the same data type.
• The elements of the array are stored in consecutive memory locations and are referenced
by an index (also known as the subscript).
int i, marks[10];
for(i=0;i<10;i++)
scanf(“%d”, &marks[i]);
ACCESSING ELEMENTS OF THE ARRAY
Array elements can be accessed using index position
Example
printf("%d", a[0]);
// Outputs 26
• Write a C program to display n numbers using array
WRITE A PROGRAM TO READ AND DISPLAY N NUMBERS
USING AN ARRAY
#include<stdio.h>
#include<conio.h>
int main()
{
int i=0, n, arr[20];
clrscr();
printf(“\n Enter the number of elements : “);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
printf(“\n Arr[%d] = “, i);
scanf(“%d”,&num[i]);
}
printf(“\n The array elements are “);
for(i=0;i<n; i++)
printf(“Arr[%d] = %d\t”, i, arr[i]);
return 0;
}
Inserting an element
x = 10;
pos = 4;
n++;
for (i = n - 1; i >= pos; i--)
{arr[i] = arr[i - 1];}
arr[pos - 1] = x;
Deleting an element
Size=5
pos = 4;
for(i=pos-1; i<size-1; i++)
{
arr[i] = arr[i + 1];
}
size--;
TWO DIMENSIONAL ARRAYS
• A two dimensional array is specified using two subscripts where one
subscript denotes row and the other denotes column.
• C looks a two dimensional array as an array of a one dimensional
array.
A two dimensional array is declared as:
data_type
First Dimension
array_name[row_size][column_size];
int marks[3][5]
Col 0 Col 1 Col2 Col 3 Col 4
Rows/Columns
Row 0 Marks[0][0] Marks[0][1] Marks[0][2] Marks[0][3] Marks[0][4]
Row 1 Marks[1][0] Marks[1][1] Marks[1][2] Marks[1][3] Marks[1][4]
Row 2 Marks[2][0] Marks[2][1] Marks[2][2] Marks[2][3] Marks[2][4]
int i, j;
for(i=0;i<2;i++)
{printf("\n");
for(j=0;j<2;j++)
printf("%d\t", arr[i][j]);}
return 0;
}
OPERATIONS ON TWO DIMENSIONAL ARRAYS
• It is used to implement the mathematical concept of Matrices.
1. Transpose
B (i, j) = A (j, i)
2. Sum
3. Difference
4. Product
mul[i][j]+=a[i][k]*b[k][j];
For example:
int *pnum;
char *pch;
float *pfnum;
int x= 10;
int *ptr = &x;
The '*' informs the compiler that ptr is a pointer variable and the int specifies that it will
store the address of an integer variable.
The & operator retrieves the address of x, and copies that to the contents of the pointer ptr.
Pointer Operators
• We can "dereference" a pointer, i.e. refer to the value of the variable to which it points
by using unary '*' operator as in *ptr. That is, *ptr = 10, since 10 is value of x.
#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);
return 0;
}
Pointers and Arrays
• The array name for ex,arr itself represents the base address of the
array, then by default arr acts as a pointer to the first element of the
array.
• arr is the same as &arr and &arr[0] in C Language
#include <stdio.h>
int main() {
int arr[5] = {3, 5, 7, 9, 11};
printf("arr : %u, Value : %d\n", arr, *arr);
printf("&arr : %u, Value : %d\n", &arr, *(arr));
printf("&arr[0] : %u, Value : %d\n", &arr[0], *( &arr[0]));
return 0;
}
POINTERS AND ARRAYS
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = &arr[0];
ptr++;
printf(“\n The value of the second element of the array is
%d”, *ptr);
Write a program to read and display an array
of n integers
#include<stdio.h> OUTPUT:
Enter the number of
int main()
elements: 3
{ int i, n; 10
int arr[10], *parr; 20
30
parr = arr; arr[0]=10
printf(“\n Enter the number of elements : “); arr[1]=20
arr[2]=30
scanf(“%d”, &n);
for(i=0; i <n; i++)
scanf(“%d”, &parr[i]); //equivalent to (ptr + i) ,&arr[i]
for(i=0; i <n; i++)
printf(“\n arr[%d] = %d”, i, *parr[i]); //equivalent to *(ptr + i),arr[i]
POINTERS AND TWO DIMENSIONAL
ARRAY
• Individual elements of the array mat can be accessed using either:
• mat[i][j] or *(*(mat + i) + j) or*(mat[i]+j);
• See pointer to a one dimensional array can be declared as,
• int arr[]={1,2,3,4,5};
• int *parr;
• parr=arr;
• Similarly, pointer to a two dimensional array can be declared as,
• int arr[2][2]={{1,2},{3,4}};
• int (*parr)[2];
• parr=arr;
POINTERS AND TWO DIMENSIONAL ARRAY
• Example:
#include<stdio.h>
Void main()
{ int arr[2][2]={{1,2},{3,4}};
int i,j, (*parr)[2]; //pointer to array
parr=arr;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t", (*(parr+i))[j]);
}
printf("\n");
}
Array of Pointers
• An array of pointers is similar to any other array in C Language.
• It is an array which contains numerous pointer variables and these
pointer variables can store address values of some other variables
having the same data type.
• Array Syntax
• data_type (array_name)[sizeof_array];
• Syntax to declare array of pointer :
• data_type (*array_name)[sizeof_array];
• Example:int *ptr[10];
Array of Pointers - Example
#include<stdio.h>
main ( ){
int a[3] = {10,20,30};
int *p[3],i;
for (i=0; i<3; i++)
p[i] = &a[i];
printf ("elements of the array are");
for (i=0; i<3; i++)
printf ("%d \t", *p[i]);
}
#include <stdio.h>
int main()
{
char *rainbow[] = {“violet", “Indigo", “blue", "green", "orange“, ”Red”, ”Yellow”};
int i;
return 0;
}
Pointers and String
• A Sequence of characters in an array is called string.
• A string always terminates with a null character (\0), which indicates the
termination of a string.
• Pointer to string in C can point to the starting address of the array that is the
first character in the array.
• Pointers can be dereferenced using the asterisk * operator to identify
characters stored at a location.
String Declaration
• char array_name[array_size] = {'a', 'b', .....};
• // OR
• char array_name[array_size];
• array_name[0] = 'a';
• array_name[1] = 'b’;
• Example
• char str[7] = {'S', 't', 'r', 'i', ‘n', 'g', '\0'}; // String
• str[4] = 'n'; // String
Pointers and String
Example:
#include<stdio.h> Syntax:
int main() data type *name;
{
char *name;
name="Amit";
printf("\n%s",name);
return(0);
}
Pointers and string
• Example
• char str[7] = "String";
• char *ptr = str;
Accessing elements
• char arr[] = "Hello";
• // pointing pointer ptr to starting address of the array arr
• char *ptr = arr;
• printf("%c ", *ptr); // H
• printf("%c ", *(ptr + 1)); // e
• printf("%c ", *(ptr + 2)); // l
• printf("%c ", *(ptr + 3)); // l
• printf("%c ", *(ptr + 4)); // o
Example
#include<stdio.h>
int main()
{
char str[11] = “CSESECTION2";
char *ptr = str;
while (*ptr != '\0’)
{
printf("%c", *ptr);
ptr++;
}
return 0;
}
Pointer and Strings
Datatype stringname[size];
#include<stdio.h> char *sname[10];
int main()
{
char *snames[5]={"Ram",“Raj","Sunil","Amar","Sam"};
int i;
printf("\nValues are:=");
for(i=0;i<5;i++)
printf("\n%s",snames[i]);
return(0);
}
2d array of strings
• Datatype name[row][column];
• char Array[3][6] = {“red", “blue", “green"};
What will be the output of the code?
• int a[] = {1, 2, 3};
• int *p = a;
• int *q = (p+1);
• int *r = (q+1);
• printf("%d", (*p+*q+*r));
int a[] = {1, 2, 3};
int *p = a, *q = &a[2];
int temp = *p;
*p = *q;
*q = temp;
for(int i=0; i<3; i++){
printf("%d ", a[i]);
}
• int a[] = {1, 2, 3};
• int *p = &a[0], *q = &a[2];
• printf("%d", q-p);
• int a[] = {1, 2, 3};
• int *p = a+1;
• printf("%d", *(++p));
• int a[] = {1, 2, 3};
• int *p = a;
• printf("%d", *(p+2));
• int x = 10;
• int *p = &x;
• *p = 5;
• printf("%d", x);
String Library functions
•strlen ()
•strcmp ()
•strcpy ()
•strrev ()
•strcat ()
•strstr ()
Strlen
syntax:strlen(stringname);
#include <stdio.h>
#include <string.h>
int main()
{
char a[20]=“hai";
char b[20]={‘h’,’a’,’i’'\0’};
printf("Length of string a = %d \n",strlen(a));
printf("Length of string b = %d \n",strlen(b));
return 0;
}
strcmp ()
syntax:strcmp(string1,string2)
Return Value Remarks
return 0;
}
strcpy ()
Syntax:strcpy(new,old)
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "C programming";
char str2[20];
// copying str1 to str2
strcpy(str2, str1);
puts(str2); // C programming
return 0;
}
strrev ()
syntax:strrev(string)
#include <stdio.h>
#include <string.h>
int main()
{
char str[50] = “basics of programming";
return 0;
}
strcat ()
syntax:strcat(dest,source)
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "This is ", str2[] = “cool";
// concatenates str1 and str2
// the resultant string is stored in str1.
strcat(str1, str2);
puts(str1);
puts(str2);
return 0;
}
strstr ()
syntax:strstr(mainstring,substring)
#include<stdio.h>
#include <string.h>
int main(){
char str[100]="this is an example";
char *sub;
sub=strstr(str,“example");
printf("\nSubstring is: %s",sub);
return 0;
}
Dynamic Memory allocation
• Sometimes the size of the array you declared may be insufficient.
• To solve this issue, you can allocate memory manually during
run-time. This is known as dynamic memory allocation in C
programming.
• To allocate memory dynamically, library functions are,
• malloc()
• calloc()
• free()
• realloc()
Malloc-Memory Allocation
• The “malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size.
• It returns a pointer of type void which can be cast into a pointer of any form.
It doesn’t Initialize memory at execution time so that it has initialized each
block with the default garbage value initially.
• ptr = (cast-type*) malloc(byte-size)
• Example:
• ptr = (int*) malloc(50 * sizeof(int));
• Since the size of int is 4 bytes, this statement will allocate 100 bytes of
memory. And, the pointer ptr holds the address of the first byte in the
allocated memory.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
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);
}
else {
printf("Memory successfully allocated using malloc.\n");
free(ptr1);
printf("Calloc Memory successfully freed.\n");
}
return 0;
}
C realloc()