DCR
DCR

Reputation: 15665

Unable to pass NULL pointer to array

#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]);

}

How can I assign node->left to ihash[0] and then be able to print out ihash[0], which should point to NULL?

Upvotes: 1

Views: 61

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51825

There are two errors in your code and a few other 'minor issues' (I've commented these in the code posted below).

The first error is that you want to create an array of pointers to nodeWords, so you will need two stars in the declaration of ihash (one star will create an array of structure objects).

Second, in ihash[0] = *node->left;, you are dereferencing node twice (once with the preceding star operator, and once again with the -> operator.

The following code fixes these issues:

#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"
}

Upvotes: 1

Related Questions