Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 3

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

UNIT 3-POINTERS AND

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

• Declaring an array means specifying three things:


The data type- what kind of values it can store ex, int, char, float
Name- to identify the array
The size- the maximum number of values that the array can hold
type name[size];
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]

• Arrays are declared using the following syntax.


1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
element element element element element element element element element element
Different method of Initialization
• int a[5]={1,2,3,4,5};
• int a[]={1,2,3,4,3,5,6};
• int a[5];
a[0]=10; a[1]=20; a[2]=30; a[3]=40; a[4]=50;
STORING VALES IN ARRAYS
Initialize the elements

Store values in the array Input values for the elements


Initialization of Arrays
Assign values to the elements
Arrays are initialized by,
type array_name[size]={list of values};
int marks[5]={90, 82, 78, 95, 88};

Assigning Values from the user

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

Array indexes start with 0

[0] is the first element.

[1] is the second element, etc.

Example

int a[] = {26, 60, 15, 100};

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

Therefore, a two dimensional mXn array is


an array that contains m*n data elements
and each element is accessed using two
subscripts, i and j where i<=m and j<=n Second Dimension

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]

Two Dimensional Array


TWO DIMENSIONAL ARRAYS CONTD..

•A two dimensional array is initialized in the


same was as a single dimensional array is
initialized.
• For example,
int marks[2][3]={90, 87, 78, 68, 62, 71};
int marks[2][3]={{90,87,78},{68, 62, 71}};
Write a program to print the elements of a 2D array
int main()

int arr[2][2] = {12, 34, 56,32};

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.

• We can perform the following operations on an m X n matrix,

1. Transpose

B (i, j) = A (j, i)

2. Sum

C (i, j)= A (i, j) + B (i, j)

3. Difference

C (i, j)= A (i, j) - B (i, j)

4. Product

mul[i][j]+=a[i][k]*b[k][j];

© Oxford University Press 2015. All rights reserved.


Multi-dimensional array
• A multi-dimensional array can be termed as an array of arrays that stores
homogeneous data in tabular form. Data in multidimensional arrays is
generally stored in row-major order in the memory.
• Syntax:
data_type array_name[x][y][z];
data_type: Type of data to be stored in each element.
array_name: name of the array
• x: Number of 2D arrays.
• y: Number of rows in each 2D array.
• z: Number of columns in each 2D array.
• Three dimensional array: int three_d[2][2][2];
Example
• int x[2][3][4] =
•{
• { {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
• { {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
• };
int x[2][2][2];

for (int i=0; i<2; i++) {


for (int j=0; j<2; j++) {
for (int k=0; k<2; k++) {
scanf("%d", &arr[i][j][k]); }
}
}
Pointers
A pointer is a variable that contains the memory location of another variable.
The general syntax of declaring pointer variable is
data_type *ptr_name;

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

Operator Operator Name Purpose


‘Value at’ Operator
Gives the value stored in
* (Indirection
that particular address
Operator)

Gives the address of the


& ‘Address’ Operator
variable
DECLARING POINTER VARIABLES
Example:
#include <stdio.h>
int main()
{
int x=10;
int *ptr=&x;
printf("X VALUE:%d", x);
printf("\nPTR VALUE:%u",ptr);
printf("\n*PTR VALUE:%d",*ptr);
return 0;
}
DE-REFERENCING A POINTER VARIABLE

• 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 = &num;
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;

for(i = 0; i < 5; i++)


{
printf("%s\n", rainbow[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

0 if strings are equal

if the first non-matching character in


>0 str1 is greater (in ASCII) than
that of str2.

if the first non-matching character in


<0 str1 is lower (in ASCII) than that
of str2.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);

// comparing strings str1 and str3


result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);

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

printf("The given string is =%s\n", str);

printf("After reversing string is =%s", strrev(str));

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

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
Calloc – Contiguous Memory Allocation
• calloc” or “contiguous allocation” method in C is used to dynamically
allocate the specified number of blocks of memory of the specified type. it is
very much similar to malloc() but has two different points and these are:
• It initializes each block with a default value ‘0’.
• It has two parameters or arguments as compare to malloc().
• ptr = (cast-type*)calloc(n, element-size);
• here, n is the no. of elements and element-size is the size of each element.
• Example:
• ptr = (float*) calloc(25, sizeof(float));
• This statement allocates contiguous space in memory for 25 elements each with the
size of the float.
Free()
• “free” method in C is used to dynamically de-allocate the memory.
• The memory allocated using functions malloc() and calloc() 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.
• free(ptr);
int main()
{

// This pointer will hold the


// base address of the block created
int *ptr, *ptr1;
int n, i;

// Get the number of elements for the array


n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


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

// Dynamically allocate memory using calloc()


ptr1 = (int*)calloc(n, sizeof(int));
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {

printf("Memory successfully allocated using malloc.\n");


free(ptr);
printf("Malloc Memory successfully freed.\n");

printf("\nMemory successfully allocated using calloc.\n");

free(ptr1);
printf("Calloc Memory successfully freed.\n");
}

return 0;
}
C realloc()

• “realloc” or “re-allocation” method in C is used to dynamically change


the memory allocation of a previously allocated memory.
• In other words, if the memory previously allocated with the help of
malloc or calloc is insufficient, realloc can be used to dynamically
re-allocate memory. re-allocation of memory maintains the already
present value and new blocks will be initialized with the default
garbage value.
• ptr = realloc(ptr, newSize);

You might also like