0

Clang returns an incompatible integer to pointer conversion returning 'int' from a function with result type 'struct node *' error when my create_node function checks whether the ptr malloc returns is NULL:

struct node *create_node(void)
{
    // mallocs memory for new node
    node *new_node = malloc(sizeof(node));

    // check to make sure not out of memory, quits if is
    if (new_node == NULL)
    {
        return 1;
    }

    // sets bool checking if word is in dictionary to false
    new_node->is_word = false;

    // set all ptrs in struct node 'branch' to NULL because don't point to anything yet
    for (int i = 0; i < 27; i++)
    {
        new_node->branch[i] = NULL;
    }

    return new_node;
}

I get it's point: the function I wrote returns a struct node and if (new_node == NULL) is true, it returns an int, but the only fix I've found is to eliminate those lines. Is it appropriate to do so and if it is, can you explain why it's ok in this context? My understanding is it's a good practice to check if the ptr malloc returns is NULL in case you're out of memory and had been doing so before I managed to create this error.

Feel free to point out anything else which is wrong and thanks in advance for the help.

1

You are actually returning an address (of a struct), not a struct or an int. By trying to return 1, you are trying to return an int, not an address.

Instead of return 1; you could still return new_node; and check whether it is NULL after it is returned. (NULL will still be a valid address, a valid "non-address" in this case.)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

3
  • Thank you--your point re: it's actually returning an address of a struct is well-taken. Re: the rest, I can do this. I know how. Appreciate you sharing a much better approach.
    – Lindsey
    Oct 2 '17 at 20:09
  • You might also find calloc() to be useful. ;-)
    – Cliff B
    Oct 2 '17 at 20:18
  • I found calloc(), but as it can return NULL, didn't interpret it to mean you could forego checking if it did. I'd be so happy if that's the case. I'm questioning having create_node() return a ptr to new_node, but can't see what else it could be. Moving the NULL check out of the function has me checking if trav->branch[ind] is NULL before and then after I call create_node() in my load function.
    – Lindsey
    Oct 3 '17 at 17:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .