Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Pointers: *ptr vs &ptr vs ptr

Tags:

c

pointers

Suppose *ptr points to a variable. What does *ptr, &ptr, and ptr each mean?

Many times, I get confused between them. Do anyone mind clarifying between those statements and give some concrete examples?

like image 355
vxs8122 Avatar asked Dec 01 '22 01:12

vxs8122


2 Answers

Take the following variables in a function.

int i = 0;
int* ptr = &i;

In the function, the memory layout could look something like:

Memory corresponding to i:

+---+---+---+---+
|       0       |
+---+---+---+---+
^
|
Address of i

Memory corresponding to ptr:

+---+---+---+---+
| address of i  |
+---+---+---+---+
^
|
Address of ptr

In the above scenario,

*ptr == i == 0
ptr == address of i == address of memory location where the vale of i is stored
&ptr == address of ptr == address of memory location where the value of ptr is stored.

Hope that makes sense.

like image 64
R Sahu Avatar answered Dec 05 '22 06:12

R Sahu


Here is a computer memory:

enter image description here

int i = 1023

If I want to print i, then I just have to do:

printf(..., i);
// out: 1023

If I want to print where i lives, then I just have to do:

printf(..., &i);
// out: 0x4

But let's say I want to remember where i lives:

int *i_ptr = &i; // i_ptr is a variable of type int *

Then I can print it this way:

printf(..., i_ptr); 
// out: 0x04

But if just print out the value of i, I need a *:

printf(..., *i_ptr); // * also doubles as a way to follow the pointer
// out: 1023

Or I can just print out where i_ptr lives:

printf(..., &i_ptr);
// out: 0x32
like image 27
Al.Sal Avatar answered Dec 05 '22 07:12

Al.Sal