Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer initialization: address or value

Tags:

c

pointers

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(...);
like image 823
davidev Avatar asked Nov 22 '19 13:11

davidev


People also ask

Does a pointer point to an address or a value?

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.

What is pointer initialization value?

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.

Do you need to initialize pointers?

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!

How pointers are declared and initialized in C?

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.


2 Answers

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).

like image 180
Bathsheba Avatar answered Sep 27 '22 23:09

Bathsheba


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));
like image 37
David Schwartz Avatar answered Sep 27 '22 22:09

David Schwartz