【发布时间】:2017-03-10 11:44:34
【问题描述】:
在我最初创建 trie 的方法中,我尝试在 malloc 内存中放置一个结构数组,而不是使用指向左/右的指针。这可能吗?原则上可以struct array[] = struct* head吗?
好的,这是我使用的代码:
typedef struct node
{
char letter;
struct node* child;
}
node;
int main(void)
{
node* head = malloc(26*sizeof(node));
if (head == NULL)
return 1;
node* temp = head;
node array[26];
array = temp;
//proceed to fill array...
我不明白的是,如果指针和array[]都是内存中的地址,为什么不能等同?
【问题讨论】:
-
不,你不能。试试看 (demo): "error: incompatible types when assignment to type ‘int[10]' from type ‘int *’”。从根本上说,指针不是数组,数组也不是指针。在某些情况下,数组只是衰减为指针。但两者是截然不同的类型。即使这是可能的,它也会导致无数的问题/UB:
arr = ptr; free(ptr); printf("%d\n", arr[0]);== 繁荣。类似的东西 -
不可以,但是你可以把head指针当成数组使用,head[0].some_member、head[1].some_other_member等等
-
您能用代码说明您要做什么吗?
-
您是创建 trie(每个节点 26 个子节点)还是 binary tree(每个节点 2 个子节点)?跨度>
-
好的,谢谢@user3386109。我想我现在明白了。
标签: c arrays pointers struct trie