c - 验证在双指针函数参数中正确使用 const

标签 c

此问题基于我为这篇文章制作的以下 C 示例:

#include <stdio.h>
#include <stdint.h>

typedef struct 
{
    uint32_t temp;
    uint32_t temp2;
} Foo_t;

static void doFoo(const Foo_t *fooAPtr, const Foo_t **fooBPtr);

static void doFoo(const Foo_t *fooAPtr, const Foo_t **fooBPtr)
{
    /* Assinging B to A just as an example */
    *fooBPtr = fooAPtr;
}

int main()
{
    Foo_t fooA = {1, 2};
    Foo_t *fooAPtr = &fooA;
    const Foo_t *fooBPtr = 0;

    doFoo(fooAPtr, &fooBPtr);

    printf("\n FooAPtr == %p, FooBPtr == %p \n", fooAPtr, fooBPtr);

    printf("\n FooAPtr == %i %i |_| FooBPtr == %i %i \n", fooAPtr->temp, fooAPtr->temp2, fooBPtr->temp, fooBPtr->temp2);

    return 0;
}

此代码可以在下面的链接中运行:

https://onlinegdb.com/rJdHGFNYB

我在质疑我的指针逻辑,想验证我对代码的假设。这是我对上面的 doFoo() 函数的解释:

fooAPtr == A constant pointer, pointing to the memory location of a structure of type Foo_t. The const denotes that the address of that memory location should not be changed

fooBPtr == A mutable pointer, pointing to an address that points to the memory location of a Foo_t structure. The const denotes that the address being pointed to cannot change?

我问这个问题很可悲,但我不能全神贯注于特定的用例。代码按预期工作,但这并不意味着它是正确的。

那么,问题来了,我对上面指针逻辑的理解是否正确?具体来说,我对 const 的使用,以及 fooBPtr 的间接层。对于上下文,doFoo() 的目标是通过函数参数将 fooBPtr 分配给 fooAPtr,而不是返回任何内容。

最佳答案

术语“常量指针”没有帮助,因为它有多种解释。

  • fooAPtr 是指向只读 数据的指针。指针本身可以更改。
  • fooBPtr 是指向只读 数据的指针。指针到指针本身可以更改。指向的指针可以改变。

请注意,在这种情况下,const 与指向的数据保持一致。从右到左阅读声明可能会有所帮助。

更多信息:What is the difference between const int*, const int * const, and int const *?

关于c - 验证在双指针函数参数中正确使用 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58412706/

相关文章:

c# - 如何使用 ffmpeg 进行视频到图像的转换?

Python - 使用 os.popen() 解析 Unix "ls"- 杀死子进程的问题

c - 使用枚举作为参数的奇怪编译行为

c - 如何检测 lib 调用者使用的语言?

c++ - 放大鼠标,考虑相机翻译? (OpenGL)

PHP脚本执行和多线程环境(PHP5扩展)

c - UDP套接字池会不会提高数据报传递的成功率和效率?

c - 2 与 "\2"之间的区别

c - 尝试构建一个函数来计算图像中的唯一像素

c - "Art of Exploitation"反汇编例子不一样(C代码)