如何为 const 结构指针的变量赋值?

How to assign values to a const structure pointer's variable?

在下面的代码中,我无法单独更改 x 和 y 的值。有人可以帮我单独分配这些值吗?

#include <stdio.h>

struct p
{  
    int x;
    int y;
};

int main()
{   
    int p2 = 55;
    int p3 = 99;
    //const struct p *ptr1 = {&p2,&p3};  --- giving the expected result
    const struct p *ptr1;
    ptr1->x = &p2;  //error
    ptr1->y = &p3;  //error
    printf("%d %d \n", ptr1->x, ptr1->y);
}

注意:我搜索过这样的例子,没找到,我运行没时间了。如果问题已经被问到,真的很抱歉浪费你的时间,请提供link以供参考。

有两个重要问题需要考虑:

  1. const struct p*是一个"pointer to const p",也就是说你不能修改它指向的实例。它可以指向一个非const对象,但你不能使用指针修改所述对象。

  2. 指针必须指向有效对象才能取消引用。

您需要创建一个有效的 p 实例,然后让指针指向它:

struct p x = {p2, p3};
const struct p *ptr1 = &x;

本例中,在自动存储中创建了一个p实例。如果更适合您的需要,您还可以使用 malloc 动态实例化一个。例如,

struct p *px = malloc(sizeof (struct p));
px->x = p2;
px->y = p3;
const struct p *ptr1 = px;

在这两个示例中,您可以分别通过 xpx 修改实例 ptr1 指向,但不能通过 ptr1.

const struct p *ptr1 = {&p2,&p3}; //  --- giving the expected result

可以编译,但是有这个警告;无论哪种方式,它都可能无法满足您的要求:

warning: incompatible pointer types initializing 'const struct p *' with an expression of type 'int *' [-Wincompatible-pointer-types]

要创建指向结构的常量指针,您可以使用:

const struct p *ptr1 = &(struct p){p2, p3};

关于 lifetime 的快速说明:

If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

由于作者似乎想更改她声明为 const 的结构,这实际上可能是一个非常相关的答案。

与这个问题直接相关的一个常见陷阱是

const struct p *ptr1

是一个指向"const struct p"的指针,也就是说指针变量ptr1以后可以改变指向不同的struct p,但是不管指向哪里,都不能对struct的成员进行写操作使用该指针(例如 ptr1->x = blah;)。

有些人可能正在寻找一个 const 指针,因此在初始化时分配一个内存后,它永远不能指向另一块内存。

那就是

struct p * const ptr2 = ptr1   // whatever ptr1 currently points to, ptr2 will point to there, from now to forever (for the lifetime / scope of ptr2).