You declare and define both variables as int
. Nothing else has an influence on the value of sizeof()
.
int a,b;
This assigns a value to one of those ints which which is very special, but it does not change anything about the fact that a
remains an int (and your cast is misleading and does not do anything at all, even less to change anything about a
).
a = (int *) malloc(sizeof(int)*2);
In order to change above line to something sensible (i.e. a meaningful use of malloc) it should be like this:
int* a;
a= malloc(sizeof(int)*2);
I.e. a
is now a pointer to int and gets the address of an area which can store two ints. No cast needed.
That way, sizeof(a)
(on many machines) will still be 4, which is often the size of a pointer. The size of what it is pointing to is irrelevant.
The actual reason for using malloc()
is determined by the goal of the larger scope of the program it is used for. That is not visible in this artificially short example. Work through some pointer-related tutorials. Looking for "linked list" or "binary tree" will get you on the right track.
What programs which meaningfully use malloc have in common is that they are dealing with data structures which are not known at compile time and can change during runtime. The unknown attributes could simply be the total size, but especially in the case of trees, the larger structure is usually unknown, too.
There is an interesting aspect to note when using malloc():
Do I cast the result of malloc?