1

I am compiling some code for a program that memoizes fibonacci numbers. The program works perfectly however when I compile in linux environment I get this warning before compiling.

line 61: warning: assignment makes pointer from integer without a cast [enabled by default]

Here is a snippet of code of where this warning is coming from, I'll try to show things of most relevance to get the best picture presented of the situation

int InitializeFunction(intStruct *p, int n)

    p->digits = (int)malloc(sizeof(int) * 1);

        if(p->digits == NULL)
            handleError("Got error");

    //making the one index in p->digits equal to n
    p->digits[0] = n;

    //incrementing a field of 'p'
    p->length++;

    //return 1 if successful
    return 1;

This function is only called twice for a very specific purpose. it is used to initialize the two base cases in the fibonacci sequence f[0] = 0 & f[1] = 1. That's it's only purpose. So if I pass by reference the address of a specific index in an array of structs it's just supposed to initialize those values:

Initializer(&someIntStruct[0], 0) ---->  after function -> someIntStruct[0] == 0
Initializer(&someIntStruct[1], 1) ---->  after function -> someIntStruct[1] == 1

thoughts?

Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
FunkyT
  • 51
  • 3
  • 8
  • 2
    1/ Don't ever cast the return value from malloc (in C anyway). 2/ Multiplying by one is what's called an identity operation, has no effect, totally unnecessary. 3/ You return 1 _always_ so I'm not sure how you detect failure unless `handleError` exits your program. – paxdiablo Jun 19 '13 at 02:53

3 Answers3

4

change

p->digits = (int)malloc(sizeof(int) * 1);

to

p->digits = (int*)malloc(sizeof(int) * 1);
vvy
  • 1,963
  • 13
  • 17
4

I suspect the warning has to do with this line:

p->digits = (int)malloc(sizeof(int) * 1);

Since malloc returns a void* , whereas you are casting it to int. I suppose p->digits is an int* ?

Try changing it to:

p->digits = (int *)malloc(sizeof(int) * 1);
yanhan
  • 3,507
  • 3
  • 28
  • 38
2

It's considered bad practice to cast the result of malloc.

And as already pointed out you're not doing it correctly either (should be (int*) ).

Community
  • 1
  • 1
Nobilis
  • 7,310
  • 1
  • 33
  • 67