0% found this document useful (0 votes)
32 views42 pages

Ds Lecture 2

The document discusses one-dimensional and two-dimensional arrays, including how to declare, initialize, pass as arguments to functions, and perform operations like traversal, insertion, deletion, and search on arrays. It also covers pointers, including declaring and initializing pointer variables, pointer operators like & and *, and using const with pointers when a function does not need to change a variable.

Uploaded by

Samuel Mengesha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views42 pages

Ds Lecture 2

The document discusses one-dimensional and two-dimensional arrays, including how to declare, initialize, pass as arguments to functions, and perform operations like traversal, insertion, deletion, and search on arrays. It also covers pointers, including declaring and initializing pointer variables, pointer operators like & and *, and using const with pointers when a function does not need to change a variable.

Uploaded by

Samuel Mengesha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Lecture 2:

Arrays, Pointers and Strings


1
Arrays: One-Dimensional Arrays

• A list of values with the same data type that are stored using a
single group name (array name).
• General array declaration statement: 
data-type array-name[number-of-items];
• The number-of-items must be specified before declaring the
array.
const int SIZE = 100;
float arr[SIZE];

2
One-Dimensional Arrays
(cont.)
• Individual elements of the array can be accessed by specifying
the name of the array and the element's index:
arr[3]
• Warning: indices assume values from 0 to number-of-items -
1!!

3
One-Dimensional Arrays
(cont.)

4
1D Array Initialization
• Arrays can be initialized during their declaration
int arr[5] = {98, 87, 92, 79, 85};
int arr[5] = {98, 87} - what happens in this case??
• What is the difference between the following two
declarations ? 
char codes[] = {'s', 'a', 'm', 'p', 'l', 'e'};
char codes[] = "sample";

codes[0] codes[1] codes[2] codes[3] codes[4] codes[5] codes[6]

s a mm p ll ee \o\0 5
1D Arrays as Arguments
• Individual array elements are passed to a function in the same
manner as other variables.
max = find_max(arr[1], arr[3]);
• To pass the whole array to a function, you need to specify the
name of the array only!!

6
#include<stdio.h>
float average(float a[100], int n);
int main() {
float a[100], res;
int i, n;
printf("Enter n:\n");
scanf("%d", &n);
for(i=0;i< n;i++) {
printf("a[%d]=",i);
scanf("%f", &a[i]); }
res = average(a,n);
printf("Average = %f", res); return 0;
}
float average(float a[10], int n) {
int i;
float sum=0.0;
for(i=0;i< n;i++) {
sum = sum + a[i]; 7
}
return(sum/n);
}
Array Operation
Traversal operation
• This operation is performed to traverse through the array elements. It prints
all array elements one after another. We can understand it with the below
program -
#include <stdio.h>  
void main() {  
  int Arr[5] = {18, 30, 15, 70, 12};  
int i;  
printf("Elements of the array are:\n");  
  for(i = 0; i<5; i++) {  
      printf("Arr[%d] = %d,  ", i, Arr[i]);  
   }  
}  
Cont.
Insertion operation
• insert one or more elements into the array. As per the
requirements, an element can be added at the beginning, end,
or at any index of the array.
#include <stdio.h>
void main() {
int array[100];
int i, n, x, pos;
printf("Enter the number of elements in the array \n");
scanf("%d", &n);
printf("Enter the elements \n");
for (i = 0; i < n; i++) {
scanf("%d", &array[i]); }
printf("Input array elements are: \n");
for (i = 0; i < n; i++) {
printf("%d ", array[i]); }
printf("\nEnter the new element to be inserted: ");
scanf("%d", &x);
printf("Enter the position where element is to be inserted: ");
scanf("%d", &pos);
n=n+1;
for(i = n-1; i >= pos; i--)
array[i+ 1]=array[i];
array[pos-1]=x;
for (i = 0; i < n; i++) {
printf("%d ", array[i]);
}
}
Deletion operation
this operation removes an element from the array and then
reorganizes all of the array elements.
#include <stdio.h>
#define MAX_SIZE 100
 
int main()
{
int arr[MAX_SIZE];
int i, size, pos;
printf("Enter size of the array : ");
scanf("%d", &size);
printf("Enter elements in array : ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
 
printf("Enter the element position to delete : ");
scanf("%d", &pos);
 
Deletion(cont.)
  if(pos < 0 || pos > size)
{
printf("Invalid position! Please enter position between 1 to %d", size);
}
else
{
for(i=pos-1; i<size-1; i++)
{
arr[i] = arr[i + 1];
}
size--;
 
printf("\nElements of array after delete are : ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}
}
 
return 0;
}

   
Search operation
• This operation is performed to search an element in the array based on the value or index.
#include <stdio.h>  
  
void main() {  
   int arr[5] = {18, 30, 15, 70, 12};  
   int item = 70, i, j=0 ;  
     
   printf("Given array elements are :\n");  
      
   for(i = 0; i<5; i++) {  
      printf("arr[%d] = %d,  ", i, arr[i]);  
   }  
    printf("\nElement to be searched = %d", item);  
   while( j < 5){  
      if( arr[j] == item ) {  
         break;  
      }  
          
      j = j + 1;  
   }  
      
   printf("\nElement %d is found at %d position", item, j+1);  
}  
Two-dimensional Arrays
• A two-dimensional array consists of both rows and columns of
elements.

• General array declaration statement: 


data-type array-name[number-of-rows][number-of-columns];

14
Two-dimensional Arrays
(cont.)
• The number-of-rows and number-of-columns
must be specified before declaring the array.
const int ROWS = 100;
const int COLS = 50;
float arr2D[ROWS][COLS];
• Individual elements of the array can be accessed
by specifying the name of the array and the
element's row, column indices.
arr2D[3][5]
15
2D Array Initialization
• Arrays can be initialized during their declaration 
int arr2D[3][2] = { {98, 87}, {79, 85}, {32, 18} };
• The compiler fills the array row by row

16
2D Arrays as Arguments
• Individual array elements are passed to a
function in the same manner as other variables. 
max = find_max(arr2D[1][1], arr2D[1][2]);
• To pass the whole array to a function, you need
to specify the name of the array only!!
• The number of columns must be specified in the
function prototype and function header.

17
#include <stdio.h>
 
float find_average(int [][2], int, int);
 
void main()
{
const numRows = 2;
const numCols = 2;
int arr2D[numRows][numCols] = {2, 18, 1, 27};
float average;
 
average = find_average(arr2D, numRows, numCols);
 
printf("The average is %d " , average);
}
18
float find_average(int vals[][2], int n, int m)
{
int i,j;
float avg;
 
avg=0.0;
for(i=0; i<n; i++)
for(j=0; j<m; j++)
avg += vals[i][j];
 
avg = avg/(n*m);
 
return avg;
}
19
2D Arrays as Arguments
(cont.)
• Important: this is essentially "call by reference":
a) The name of the array arr2D stores the address of arr2D[0] (i.e.,
&arr2D[0])
b) arr2D[0] stores the address of the first element of the array
arr2D[0][0] (&arr2D[0][0])
c) Every other element of the array can be accessed by using its
indices as an offset from the first element.
A[i][j]= Base + ((i * n) + J) * Size
Where n is number of columns

20
Pointer Variable Declarations and
Initialization
countPtr count
• Pointer variables 7
count

7
• Pointers contain the address of a variable that has a
 
specific value (indirect reference)
• Indirection
• Referencing a pointer value
• Pointer declarations
• * indicates variable is a pointer
int *myPtr;
declares a pointer to an int, a pointer of type int
*
• Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2;
Pointer Variable Declarations and
Initialization
• Can declare pointers to any data type
• Pointers initialization
• Initialized to 0, NULL, or an address
• 0 or NULL points to nothing
Pointer Operators
• & (address operator)
• Returns the address of its operand
• Example
int y = 5;
int *yPtr;
yPtr = &y; // yPtr gets address of y
• yPtr “points to” y

y yptr y
5 500000 600000 600000 5
yPtr

address of y
is value of
yptr
Pointer Operators
• * (indirection/dereferencing operator)
• Returns the value of what its operand points to
• *yPtr returns y (because yPtr points to y).
• * can be used to assign a value to a location in memory
*yptr = 7; // changes y to 7
• Dereferenced pointer (operand of *) must be an lvalue (no
constants)
• * and & are inverses
• Cancel each other out
*&myVar == myVar
and
&*yPtr == yPtr
#include <stdio.h>

void main()
{
  int a; /* a is an integer */
  int *aPtr; /* aPtr is a pointer to an integer */
  a = 7;
  aPtr = &a; /* aPtr set to address of a */
  printf( "The address of a is %p\nThe value of aPtr is %p", &a, aPtr );
  printf( "\n\nThe value of a is %d\nThe value of *aPtr is %d", a, *aPtr );
  printf( "\n\nShowing that * and & are inverses of each other.\
n&*aPtr = %p" "\n*&aPtr = %p\n", &*aPtr, *&aPtr );
} The address of a is 006AFDF4
The value of aPtr is 006AFDF4
The value of a is 7
The value of *aPtr is 7
Showing that * and & are inverses of each other.
&*aPtr = 006AFDF4
*&aPtr = 006AFDF4
Using the Const Qualifier with Pointers
• const qualifier
• Variable cannot be changed
• const used when function does not need to change a
variable
• Attempting to change a const variable is a compiler
error
• const pointers
• Point to same memory location
• Must be initialized when declared
int *const myPtr = &x;
• Constant pointer to a non-constant int
const int *myPtr = &x;
• Non-constant pointer to a constant int
const int *const Ptr = &x;
• Constant pointer to a constant int
#include<stdio.h>
int main(void) {
int var1 , var2 ;
int *const ptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}

Error E2024 Fig05_13.c 15: Cannot modify a const object in function


main()
Pointer Expressions and Pointer Arithmetic
• Pointer arithmetic
• Increment/decrement pointer (++ or --)
• Add/subtract an integer to/from a pointer( + or += , - or -=)
• Pointers may be subtracted from each other
• Pointer arithmetic is meaningless unless performed on an array
• 5 element int array on a machine using 4 byte ints
• vPtr points to first element v[ 0 ], which is at location 3000
 
• vPtr = 3000
• vPtr += 2; sets vPtr to 3008
• vPtr points to v[ 2 ] location
3000 3004 3008 3012 3016

v[0] v[1] v[2] v[3] v[4]

pointer variable
vPtr
Pointer Expressions and Pointer Arithmetic

• Subtracting pointers
• Returns the number of elements between two
addresses
vPtr2 = v[ 2 ];
vPtr = v[ 0 ];
vPtr2 - vPtr == 2
• Pointer comparison
• Test which pointer points to the higher numbered array
element
• Test if a pointer points to 0 (NULL)
if ( vPtr == ‘0’ )
statement
The Relationship Between Pointers and
Arrays
• Arrays and pointers closely related
• Array name like constant pointer
• Pointers can do array subscripting operations
• Having declared an array b[ 5 ] and a pointer bPtr
• bPtr is equal to b
bptr == b
• bptr is equal to the address of the first element of b
bptr == &b[ 0 ]
The Relationship Between Pointers and
Arrays

• Accessing array elements with pointers


• Element b[ n ] can be accessed by *( bPtr + n )
• Called pointer/offset notation
• Array itself can use pointer arithmetic.
• b[ 3 ] same as *(b + 3)
• Pointers can be subscripted (pointer/subscript notation)
• bPtr[ 3 ] same as b[ 3 ]
Arrays of Pointers
• Arrays can contain pointers
• Commonly used to store an array of strings
char *suit[ 4 ] = {"Hearts", "Diamonds",
"Clubs", "Spades" };
• Each element of suit is a pointer to a char * (a string)
• The strings are not in the array, only pointers to the
 
strings are in the array
• suit array has a fixed size, but strings can be of any
size
suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’

suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’

suit[2] ’C’ ’l’ ’u’ ’b’ ’s’ ’\0’

suit[3] ’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’


Fundamentals of Characters and Strings
• Character constant
• Integer value of a character
• Single quotes
• 'z' is the integer value of z, which is 122
• String
• Series of characters treated as one unit
• Can include letters, digits, special characters +, -, * ...
• String literal (string constants)
• Enclosed in double quotes, for example:
"I like C++"
• Array of characters, ends with null character '\0'
• Strings are constant pointers (like arrays)
• Value of string is the address of its first character
Fundamentals of Characters and Strings
• String assignment
• Character array:
char color[] = "blue";
• Creates 5 element char array, color, (last element is '\0')
• variable of type char *
char *colorPtr = "blue";
• Creates a pointer to string “blue”, colorPtr, and stores it somewhere in
memory
Dynamic Memory Allocation:

• The technique through which a program can be obtaining


space in the RAM during the execution of the program and not
during compilation is called dynamic memory allocation.
Functions of Dynamic Memory Allocation:
malloc() function:
• malloc() function is used for allocating block of memory at
runtime. This function reserves a block of memory of given
size and returns a pointer of typo void.
• This means that one can assign it to any type of pointer using
typecasting. If it fails to locate enough space it returns a NULL
pointer.
Syntax: 
void *malloc(size_t size)
ptr = (int*) malloc(5* sizeof(int));
#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");
  
              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]);
        }
    }
  
    return 0;
}
Cont.
calloc() function:
• calloc() is another memory allocation function that is used for
allocating memory at runtime. calloc() initializes the allocated
memory to zero but, malloc() doesn’t.
• calloc() function is normally used for allocating memory to
derived data types such as arrays and structures. If it fails to
locate enough space it returns a NULL pointer.
Syntax: 
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each
element.
ptr = (int*) calloc(25, sizeof(int));
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int* ptr;
    int n, i;
    n = 5;
    printf("Enter number of elements: %d\n", n);
      ptr = (int*)calloc(n, sizeof(int));
  
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
          printf("Memory successfully allocated using calloc.\n");
  
        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]);
        }
    }
  
    return 0;
}
Cont.
realloc() function:
• realloc () function modifies the allocated memory size by malloc () and calloc () functions to
new size. If enough space doesn’t exist in memory of current block to extend, new block is
allocated for the full size of reallocation, then copies the existing data to new block and then
frees the old block.
Syntax: 
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
ptr = realloc(ptr, 10* sizeof(int))

free() function:
• When a program comes out, operating system automatically release all the memory
allocated by the program but as a good practice when there is no need of memory anymore
then the memory should be released by calling the function free().free() function frees the
allocated memory by malloc (), calloc (), realloc () functions and returns the memory to the
system.
Syntax: 
free(ptr);
#include <stdio.h>
#include <stdlib.h>
  
int main()
{
    int* ptr;
    int n, i;
      n = 5;
    printf("Enter number of elements: %d\n", n);
    ptr = (int*)calloc(n, sizeof(int));
     if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
          printf("Memory successfully allocated using calloc.\n");
          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]);
        }
  
  }
             n = 10;
        printf("\n\nEnter the new size of the array: %d\n", n);
          ptr = realloc(ptr, n * sizeof(int));
            printf("Memory successfully re-allocated using realloc.\n");
  
                for (i = 5; 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);
    }
  
    return 0;
}

You might also like