guskenny83
guskenny83

Reputation: 1373

pointer from integer without a cast warning

Can someone please explain to me why the following code will compile fine when it is all in the one C file, but when i put the make_queue_data() function into another C file and compile it, it gives me an "assignment makes pointer from integer without a cast" warning?

#include <stdlib.h>
#include <stdio.h>

typedef struct pqueue_data_t
{
    int priority;
    void *queue_data;
} pqueue_data_t;

void*
safe_malloc (size_t size)
{
    void *mem_block = NULL;
    if ((mem_block = calloc (1, size)) == NULL) {
        fprintf (stderr, "ERROR: safe_malloc() cannot allocate memory.");
        exit (EXIT_FAILURE);
    }
    return (mem_block);
}

pqueue_data_t * 
make_queue_data(void *data, int priority)
{
    pqueue_data_t *pdata;
    pdata = (pqueue_data_t *) safe_malloc(sizeof(pqueue_data_t));
    pdata->priority = priority;
    pdata->queue_data = data;
    return (pdata);
}

int *
alloc_data (int val)
{
    int *rv = (int *)safe_malloc(sizeof(int));
    *rv = val;
    return (rv);
}

int
main (int argc, char **argv)
{
    pqueue_data_t *temp;
    temp = make_queue_data(alloc_data(34), 0); /* problem line */
    printf("%d\n", *((int *)temp->queue_data));
    return EXIT_SUCCESS;
}

this isnt the whole of my code, i just cut and pasted the relevant parts into the one.

any help would be greatly appreciated, as i have been bashing my head against this wall for a couple of hours trying to find where the problem is..

Upvotes: 0

Views: 539

Answers (2)

Kninnug
Kninnug

Reputation: 8053

Make sure the function prototype is available in all source files that use the function. If you define a function in one file and use it in another the other file still needs to know the function prototype.

When the compiler sees a function-call that it knows no prototype or definition of it assumes the function to have a return type int, when you assign this to a pointer the compiler warns you about it. This is also the reason you should never cast the result of malloc in case you forget to include stdlib.h.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409136

It might be (and here I'm guessing) because you don't have a prototype of safe_malloc in the other source file.

Or it might be because you don't have the pqueue_data_t defined in the other source file (it should probably be in a header file instead).

Upvotes: 3

Related Questions