int *ptr;
ptr=(int *)malloc(sizeof(int)*2);
ptr=100; /*What will happen if I put an asterisk(*) indicating *ptr=100? */
ptr++;
printf("ptr=%d",*ptr);
free(ptr);
So, I wanted the pointer to increment. I allocated a size of 4(2*2) for the pointer. But I couldn't understand how the pointer increments only by 2. And if I put an asterisk int the 3rd line,that is *ptr=100; It shows something else.
If you have int * ptr
, then ptr++
increments the pointer by the size of a single int
. If int
is two bytes on your platform, that's why it increments by two.
*ptr = 100
would store the value 100
at the int
pointed to by ptr
, i.e. the first of the two int
s that you allocated with your malloc()
call.
ptr = 100
will attempt to assign the memory address 100
to ptr
, which is almost certainly not what you want, as you would lose your reference to the memory you just malloc()
ed, and what is at memory location 100
is probably not meaningful for you or accessible to you.
As it currently stands, if you were to do *ptr = 100
and then ptr++
, your printf()
call would result in undefined behavior since you'd have incremented the pointer to point to uninitialized memory (i.e. the second of the two int
s you allocated with your malloc()
call), whose contents you then attempt to output.
(*ptr)++
on the other hand would increment that 100
value to 101
, leave the value of ptr
unchanged, your printf()
call would be fine, and output 101
. The second of the two int
s you allocate would still remain uninitialized, but that's no problem if you don't attempt to access it.
Also, don't cast the return from malloc()
, ptr=(int *)malloc(sizeof(int)*2)
should be ptr=malloc(sizeof(int)*2)
, or even better, ptr = malloc(sizeof(*ptr) * 2)
;