arrays - 无法将 NULL 指针传递给数组
问题描述
#include <stdio.h>
#include <stdlib.h>
typedef struct nodeWords
{
char * word;
int index;
struct nodeWords *left;
struct nodeWords *right;
} nodeWords;
int main(void)
{
nodeWords * node = malloc(sizeof(*node));
printf("%lu\n",sizeof(*node));
node->left = NULL;
node->right = NULL;
nodeWords * ihash = malloc(2 * sizeof(*ihash));
printf("%p \n", node->left);
//this part not working
ihash[0] = *node->left;
printf("%p\n",ihash[0]);
}
我如何分配node->left
给ihash[0]
然后能够打印出来ihash[0]
,应该指向哪个NULL
?
解决方案
您的代码中有两个错误和其他一些“小问题”(我在下面发布的代码中对此进行了评论)。
第一个错误是您要创建一个指向 的指针数组,因此在声明中nodeWords
需要两颗星(一颗星将创建一个结构对象ihash
数组)。
其次,在 中ihash[0] = *node->left;
,您要取消引用node
两次(一次是使用前面的星号运算符,一次是使用->
运算符。
以下代码修复了这些问题:
#include <stdio.h>
#include <stdlib.h>
typedef struct nodeWords {
char* word;
int index;
struct nodeWords* left;
struct nodeWords* right;
} nodeWords;
int main(void)
{
nodeWords* node = malloc(sizeof(*node));
printf("%zu\n", sizeof(*node)); // Should really use "%zu" for size_t
node->left = NULL;
node->right = NULL;
nodeWords** ihash = malloc(2 * sizeof(*ihash)); // You want an array of POINTERS so you need two ** in the type!
printf("%p \n", (void*)node->left); // Pedantic: %p expects a void*
//this part not working
ihash[0] = node->left; // The "*" preceding "node" was an error: the "->" inherentlt derefernces node
// ihash[0] = (*node).left; // An alternative way of dong the same thing
printf("%p\n", (void*)ihash[0]); // Pedantic: %p expects a void*
// Don't forget to free the allocated memory...
free(ihash);
free(node);
return 0; // Always good practice to put this EXPLICIT return statement in your "main"
}
推荐阅读
- selenium - 在单独的选项卡中打开链接
- flutter - Flutter如何通过屏幕打印值?
- python - 在python中对齐unicode字符的问题
- flutter - 如何在另一个无状态小部件中导航 BottomNavigationBar
- javascript - Vue - 如何显示本地数据
- mysql - 如果我有主键 ID,我需要 AND 子句吗?
- node.js - promise.resolve() 链给出奇怪的答案
- linux - 在文本文件中显示当前日期的脚本?
- xamarin.forms - xamarin.forms httpclient 多次更改 BaseAddress 运行时
- html - 如何基于子元素将整个元素居中?