为什么这不会生成警告或错误

Ele*_*ner 4 c pointers constants

我有一个需要指针的函数,但我不小心将它声明为 const。该函数(故意)更改指针值 - 实际指针而不是指针指向的数据。

我想知道为什么这不会产生警告......

static void CalcCRC(const uint32_t *pData, uint8_t noWords)
{
    
    // Do some other stuff....

    pData = pData + noWords;

    // Do some other stuff....

}
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 7

该声明const uint32_t *pData创建了一个指向 a 的指针const uint32_t,这意味着该指针指向的是const,而不是指针本身,因此修改该指针是合法的。

如果你做了这样的事情:

*pData = 0;
Run Code Online (Sandbox Code Playgroud)

然后你会得到一个修改类型的错误const


And*_*zel 6

声明

const uint32_t *pData;
Run Code Online (Sandbox Code Playgroud)

会生成*pDataconst,但不会生成pDataconst 本身。换句话说,指针所指的内容被认为是 const(当通过指针访问时),但指针本身不是 const。

如果你希望指针本身是常量,那么你应该写

uint32_t * const pData;
Run Code Online (Sandbox Code Playgroud)

反而。

如果你想让指针本身以及指针所引用的内容成为 const,那么你应该使用以下声明:

const uint32_t * const pData;
Run Code Online (Sandbox Code Playgroud)