首页 > 解决方案 > 无法将 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->leftihash[0]然后能够打印出来ihash[0],应该指向哪个NULL

标签: arrayscpointers

解决方案


您的代码中有两个错误和其他一些“小问题”(我在下面发布的代码中对此进行了评论)。

第一个错误是您要创建一个指向 的指针数组,因此在声明中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"
}

推荐阅读