<无法打印内存>注意:指针指向此处

  • 本文关键字:指针 打印 内存 注意 c
  • 更新时间 :
  • 英文 :


我是c的初学者。

我正在尝试使用以下代码创建一个简单的哈希表。但是,发生以下错误。任何人都可以向我解释为什么?

运行时错误:存储到类型"结构节点 *"的未对齐地址0x0000ffffffff,这需要 8 个字节对齐 0x0000ffffffff:注意:指针指向此处 分段错误

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Hashnode
{
int size;
struct Node** hashnode;
}Hashtable;

typedef struct Node
{
char* word;
struct Node* next;
}Node;
int main(void)
{
Node* node = malloc(sizeof(Node));
node->word = "Elvin";
node->next = NULL;
printf("First Node created successfully!...n");
Hashtable hasht;
hasht.size = 10;
for (int i = 0; i < hasht.size; i++)
{
hasht.hashnode[i] = NULL;
printf("the address of the %i hasnode is: %pn", i, hasht.hashnode[i]);
}
printf("The hashtable is created successfully!...n");

后续问题

更正上述代码后,我想将哈希节点与节点链接起来。由于hashnode是Node**(指向节点指针的指针(,因此hasnode的值应该是节点指针(即&node(的地址。我的代码如下。

但是,它向我显示了一个错误,即不兼容的指针类型从"节点**"(又名"结构节点**"(分配给"结构节点*";删除&。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Hashnode
{
int size;
struct Node** hashnode;
}Hashtable;

typedef struct Node
{
char* word;
struct Node* next;
}Node;
int main(void)
{
Node* node = malloc(sizeof(Node));
node->word = "Elvin";
node->next = NULL;
printf("First Node created successfully!...n");
Hashtable hasht;
hasht.size = 10;
hasht.hashnode = malloc(sizeof(*hasht.hashnode)*hasht.size);
for (int i = 0; i < hasht.size; i++)
{
hasht.hashnode[i] = NULL;
printf("the address of the %i hashnode is: %pn", i, hasht.hashnode[i]);
}
printf("The hashtable is created successfully!...n");
int key = 3;
hasht.hashnode[key] = &node;
}

知道我做错了什么吗?

你忘了初始化指针表:

hasht.size = 10;
// you need to allocate the array of pointers
hasht.hashnode = malloc(sizeof(*hasht.hashnode)*hasht.size);
// now proceed with your loop
for (int i = 0; i < hasht.size; i++)
{

因此,当尝试初始化指针时,您会在树林中写入一个未定义的位置:未定义的行为。

最新更新