dj2k dj2k - 1 month ago 5
C Question

How does this pointers example not produce errors?

I am just starting to learn about pointers using the C programming language and I am crossed up on this particular code example they have in the book I'm using:

#include <stdio.h>
#define SIZE 10

void bubbleSort( int * const array, const size_t size ); // prototype

int main( void )
{
// initialize array a
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };

size_t i; // counter

puts( "Data items in original order" );

// loop through array a
for ( i = 0; i < SIZE; ++i )
{
printf( "%4d", a[ i ] );
} // end for

bubbleSort( a, SIZE ); // sort the array

puts( "\nData items in ascending order" );

// loop through array a
for ( i = 0; i < SIZE; ++i )
{
printf( "%4d", a[ i ] );
} // end for

puts("");

return 0;
}

// sort an array of integers using bubble sort algorithm
void bubbleSort( int * const array, const size_t size )
{

void swap( int *element1Ptr, int *element2Ptr ); // prototype
unsigned int pass; // pass counter
size_t j; // comparison counter

// loop to control passes
for ( pass = 0; pass < size - 1; ++pass )
{

// loop to control comparisons during each pass
for ( j = 0; j < size - 1; ++j )
{

// swap adjacent elements if they’re out of order
if ( array[ j ] > array[ j + 1 ] )
{
swap( &array[ j ], &array[ j + 1 ] );
} // end if
} // end inner for
} // end outer for
} // end function bubbleSort

// swap values at memory locations to which element1Ptr and
// element2Ptr point
void swap( int *element1Ptr, int *element2Ptr )
{
int hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
} // end function swap


What I am not understanding is why is this not giving any errors, since I see that in the parameters for the bubbleSort function, there is a
const
in front of array, making the array it's pointing to a
const
so that it cannot be changed. But in this function, we are swapping the elements from the array so shouldn't that produce an error due to the fact that changes to the array are made? I'm assuming that it maybe I'm not understanding precisely how pointers work in this context?

Answer

The meaning of int * const array is that the pointer itself cannot be modified but the value of array can be modified. In other words, imagine we have a block in memory with will hold the address to another block of memory. in the case that const comes after type, the value in this block that holds the address cannot be changed but the other memory block with actual array values can be changed. So you cannot instantiate a new part of memory and put its address into array.

Comments