初学者问题:我认为我了解指针(int *p,x = 1,p =& x)有些有些,但显然涉及到" ->"时,却没有。
typedef struct node
{
bool is_word;
struct node* children[27];
}
node;
和
node* root = calloc(1, sizeof(node));
printf("address:%pn", &root->children[1]);
printf("content%pn", root->children[1]);
printf("n");
root->children[1] = &root->children[1];
printf("address:%pn", &root->children[1]);
printf("content%pn", root->children[1]);
简单地说,我有一个指针,我希望它存储自己的地址。但这给了我:
error: incompatible pointer types assigning to 'struct node *'
from 'struct node **'; remove & [-Werror,-Wincompatible-pointer-types]
root->children[1] = &root->children[1];
^ ~~~~~~~~~~~~~~~~~~
我尝试了一些组合,到目前为止都没有工作。我想念什么?
根据您对Ishay答案的评论,您想实现 content ==地址 ...
很容易获得,但是我想警告您为什么不应该这样做。如果node->children[1]
指向其自己的地址,则取消指针是未定义的行为,因为存在不是 a node
而不是node *
。这意味着,一旦有了它,对*(node->children[1])
的任何访问均可读取或写入,甚至使用node->children[1]->...
语法,则根据严格的别名规则是明确的未定义行为(搜索so so so so so so so so so so 严格的别名规则 for for有关此的更多详细信息)。
一旦您被警告,C语言对程序员非常有信心,并且允许您进行非感觉的事情:
root->children[1] = (void *) &root->children[1]; /* or root->children[1] = (node *) &root->children[1]; */
printf("address:%pn", &root->children[1]);
printf("content%pn", root->children[1]);
将显示您想要的东西。这是因为始终允许将指针复制到(void *)
,并且可以将void *
复制到任何其他指针。C标准要求(前提是没有对齐问题,并且在您的示例中不应存在)这些指针分配是完美定义的,并且:
node ** p = (node **) root->children[1];
也被定义,p
必须指向root->children[1]
。换句话说,您可以将指向一种指向一种指向另一种指针的指针,然后将其抛弃为您的初始值,但您的>不得 derefence 不正确指针。
更改
root->children[1] = &root->children[1];
root->children[1] = root->children[1];
它不起作用的原因与错误消息中所述 -
root->children[i]
是类型节点*,这意味着root->儿童[i]本身是一个指向类型struct node
的数据的内存地址。
话虽如此,为什么要存储内存地址?
考虑以下示例:您是输入INT的指针:
int *ptr
现在,如果您需要PTR的内存地址,则可以只使用printf("%p", ptr)
如果需要数据,只需printf("%d", *ptr)