What is the difference between the following two statements?
ptr = malloc (400);
and
ptr = malloc (100 * sizeof(int))
How does it work? Is there any difference between them?
types of ptr 'int'
What is the difference between the following two statements?
ptr = malloc (400);
and
ptr = malloc (100 * sizeof(int))
How does it work? Is there any difference between them?
types of ptr 'int'
It depends on your architecture. On a 64-bit machine, the int
size should be 8 bytes and 4 bytes on a 32-bit. Though it is not a rule, your 64-bit compiler might register having 4 bytes instead.
So the difference is that the allocated memory might vary depending on the architecture you are targeting and what the compiler decides.
This is also true for the size of your pointers.
No there should not be any. Malloc allocates contiguous memory chunk in bytes at runtime, so as long as integer takes 4 bytes, then no problem.
You can also refer this, for more clarity.
Also since you did not mention the type of pointer you are using .. the 2 ways makes no difference. Suppose you wanted an integer type then here is an example:
int *ptr;
ptr = malloc(100 * sizeof *ptr);
The first form allocates 400 bytes.
The second form allocates enough space for 100 int
objects.
These are not necessarily the same thing, as the size of an int
can be 2, 4, or more bytes wide depending on the platform.
If you need to set aside space for N
objects of a given type, use the following idiom:
T *ptr = malloc( N * sizeof *ptr ); // for any object type T
sizeof *ptr
is equivalent to sizeof (T)
.