top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Pointer assignment in C?

+3 votes

See the following two statement

float *ptr = malloc( sizeof(*ptr) );


float *ptr;
ptr = malloc( sizeof(*ptr) );

In first case we allocate the memory to *ptr and in the second to ptr, why is such a difference.

posted Nov 6, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
Best answer

In term of final result both are same.

First one is pointer is got initialized (assigned an initial value) at the time of declaration.

Second one is declaration then separately initialized to the memory location given by malloc().


float  *ptr = malloc(sizeof(*ptr));  is nothing but
float *ptr  (declaration)  and  (ptr = malloc(sizeof(*ptr)) ) (initialization)

It definitely not, what you are thinking.

Because :

ptr is of type  (float *)  which is a pointer.
*ptr is of type  (float)   which is not a pointer,  so it can't points to the address given by malloc()

You can consider your first statement like this:

float  *   ptr = malloc(sizeof(*ptr);   // I think this will clear your doubt.
answer Nov 6, 2014 by Arshad Khan
–1 vote

in first case the created memory will be saved at the *ptr but in second case ptr will be the memory address of the newly created memory.

answer Nov 6, 2014 by Kumar Shishir
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.