1

i am trying to allocate memory for integer but i get a warning assignment makes integer from pointer without a cast and when i do a cast for an int i get a warning cast from pointer to integer of different size

here is my code for first :

int i;
for(i = 0 ; i < gNumOfAllFiles ; i++)
{
    int *v=(int *)malloc(1*sizeof(int));
    v=0;
    dependencies[i].visited =(int)v;
}

or

dependencies[i].visited =v

The dependencies[i] is a struct contains field int visited and i am trying to initilize it by 0

KaramJaber
  • 851
  • 5
  • 13
  • 24
  • 1
    Writting to a pointer: `*v = 0`. Reading from a pointer: `visited = *v`. – Guilherme Bernal Nov 11 '13 at 14:47
  • Why are you trying to assign a pointer-to-int to an int? What's your intent? –  Nov 11 '13 at 14:47
  • 7
    Also, [don't cast the return value of `malloc()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)! –  Nov 11 '13 at 14:48
  • This code will leak memory: if `gNumOfAllFiles` is 1000, you'll allocate 1000 ints, but never free them. For each `malloc` call, there has to be a `free` to match it – Elias Van Ootegem Nov 12 '13 at 13:06

3 Answers3

5

This is wrong because it tries to cast the pointer address as an integer:

dependencies[i].visited =(int)v;

Do this instead (to get the contents pointed at by v):

dependencies[i].visited =*v;

edit: also, to set the contents of the pointer use *v=0; instead of v=0;

grasshopper
  • 3,988
  • 3
  • 23
  • 29
1

v contains the address of a piece of memory.
(int)v casts this address to an integer, which is a mostly-meaningless operation.

You want to get the value that occupies the memory at this address, using the dereference operator:

int value = *v;

Similarly, v = 0 makes your pointer point to memory address 0 (which is NULL), and leaks the memory you allocated using malloc().

You can store a value in the memory pointed to by the pointer using the dereference operator:

*v = 0;
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

use dependencies[i].visited =*v;