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

4
  • 1
    Writting to a pointer: *v = 0. Reading from a pointer: visited = *v. Commented Nov 11, 2013 at 14:47
  • Why are you trying to assign a pointer-to-int to an int? What's your intent? Commented Nov 11, 2013 at 14:47
  • 7
    Also, don't cast the return value of malloc()! Commented Nov 11, 2013 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 Commented Nov 12, 2013 at 13:06

3 Answers 3

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;

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

0

use dependencies[i].visited =*v;

1 Comment

dependencies[i].visited =*v; isn't exactly a good idea right after he assigns v = 0...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.