Reputation: 56
I have a doubt in dynamic memory allocation (malloc
)
Say
ivar=(int*)malloc(1*sizeof(int));
What the above code will do? Will it create address for allocations?
Also which is the standard way to get values in malloc? (Say i as loop variable)
scanf("%d",&ivar[i]);
OR
scanf("%d",ivar+i);
int main()
{
int *ivar;
ivar=(int*)malloc(1*sizeof(int));
printf("%u",ivar); // outputs 2510
printf("%u",&ivar);// outputs 65524
} // please explain why it is…
Thanks in advance.
Upvotes: 0
Views: 77
Reputation: 275
The memory allocated using malloc is created in heap section of RAM.
ivar=(int*)malloc(1*sizeof(int));
The syntax for malloc is
void *malloc(size_t size);
(1*sizeof(int)) gives 4 bytes, so 4 bytes is allocated in Heap.
You cannot directly access memory of heap, so ivar pointer is used to access it.
When you write
printf("%p",ivar); // outputs 2510
printf("%p",&ivar);// outputs 65524
Both of these gives address, first one gives address of the location pointer is pointing at, second one gives address of the pointer
scanf("%d",&ivar[i]);
and
scanf("%d",ivar+i);
both are equal, so you can use either one of them.
Upvotes: 1