1 c pointers structure constants
在下面的代码中,我无法单独更改 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);
}
Run Code Online (Sandbox Code Playgroud)
注意:我已经搜索过这样的例子,但找不到,而且时间不多了。如果问题已经被问到,我真的很抱歉浪费您的时间,请向我提供相同的链接以供参考。
由于作者似乎想要更改她声明为 const 的结构,因此这实际上可能是一个非常相关的答案。
与这个问题直接相关的一个常见问题是
const struct p *ptr1
Run Code Online (Sandbox Code Playgroud)
是一个指向“const struct p”的指针,这意味着指针变量 ptr1 可以更改并稍后指向不同的 struct p,但无论它指向哪里,您都无法使用该指针写入该结构的成员(例如ptr1->x = blah;)。
有些人可能正在寻找一个常量指针,因此在初始化时被分配一个内存后,永远不能指向另一块内存。
那将是
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).
Run Code Online (Sandbox Code Playgroud)