【问题标题】:How does this pointers example not produce errors? [duplicate]这个指针示例如何不产生错误? [复制]
【发布时间】: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 表示arrayconst,而不是它指向的东西。 array 是一个糟糕的指针名称,我建议更改它!
  • @M.M 对此感到抱歉,我只是简单地输入了书中示例中显示的内容

标签: c arrays function pointers constants


【解决方案1】:

int * const array的意思是指针本身不能修改,但是数组的值可以修改。换句话说,假设我们在内存中有一个块,它将保存另一个内存块的地址。如果const 出现在类型之后,则该块中保存地址的值不能更改,但可以更改具有实际数组值的另一个内存块。所以你不能实例化一个新的内存部分并将其地址放入array

【讨论】:

  • 哦,哇,现在我觉得自己很傻。在阅读了您的解释后,我意识到说int * const arrayconst int *array 是有区别的。在我的书中,有另一个示例旨在创建一个指向常量数据的非常量指针,该指针读取为const char *sPtr,出于某种原因,我认为这与我的问题中的示例相似。
  • @dj2k 这是一个诚实的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 2017-02-25
  • 2020-10-11
  • 1970-01-01
  • 2016-03-30
相关资源
最近更新 更多