【发布时间】:2017-02-21 23:37:38
【问题描述】:
我刚刚开始学习使用 C 编程语言的指针,我对我正在使用的书中的这个特定代码示例感到困惑:
#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
我不明白为什么这没有给出任何错误,因为我看到在bubbleSort函数的参数中,数组前面有一个const,使它指向一个const的数组使其无法更改。但是在这个函数中,我们正在交换数组中的元素,所以不应该因为对数组进行更改而产生错误吗?我假设我可能没有准确理解指针在这种情况下是如何工作的?
【问题讨论】:
-
const array表示array是const,而不是它指向的东西。array是一个糟糕的指针名称,我建议更改它! -
@M.M 对此感到抱歉,我只是简单地输入了书中示例中显示的内容
标签: c arrays function pointers constants