I have a question regarding pointer initialization in C.
I understand that *ptr
will give the value of that pointer is pointing to.
ptr
will give you the address.
Now I got following syntax:
int *ptr = (int *) malloc(sizeof(*ptr));
Why is *ptr
being initialized with an address of the Heap and not a value? malloc()
returns an address right?
Shouldn't it be:
int *ptr;
ptr = malloc(...);
Put another way, the pointer does not hold a value in the traditional sense; instead, it holds the address of another variable. A pointer "points to" that other variable by holding a copy of its address. Because a pointer holds an address rather than a value, it has two parts. The pointer itself holds the address.
Value-initialization of a pointer initializes it to a null pointer value; therefore both initializer lists are equivalent. To zero-initialize an object or reference of type T means: if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T.
All pointers, when they are created, should be initialized to some value, even if it is only zero. A pointer whose value is zero is called a null pointer. Practice safe programming: Initialize your pointers!
While declaring/initializing the pointer variable, * indicates that the variable is a pointer. The address of any variable is given by preceding the variable name with Ampersand & . The pointer variable stores the address of a variable. The declaration int *a doesn't mean that a is going to contain an integer value.
With *ptr
, *
is acting as the dereferencing operator.
With int *ptr
, *
is acting as part of the type declaration for ptr
.
So the two things are entirely different, even though *
is used. (Multiplication and comment blocks are further uses of *
in C).
In that line, int *
is the type.
int *ptr = (int *) malloc(sizeof(*ptr));
Is just this compressed into one line:
int *ptr;
ptr = (int *) malloc(sizeof(*ptr));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With