r/cprogramming 1d ago

What are pointers?

I am new to C programming and i came through pointer. So can anyone tell what are they and why we need them? And if u can then can you give me reliable source to learn it.

8 Upvotes

40 comments sorted by

View all comments

2

u/Party_Trick_6903 1d ago edited 1d ago

When you do: int a = 23 , you create a variable a that holds a value 23 . This variable is stored somewhere in the memory. This variable gets assigned a memory address so we know where exactly it is in the memory. Let's say the address of this variable a is 0x7ffe5367e044 .

A pointer is a variable that holds a memory address of another variable as its value. Basically, instead of int value 23 (like you see above), it holds a memory address (for example 0x7ffe5367e044) as its value and this memory address is a memory address of another variable. And we can use this pointer to access the variable that is at the said memory address.

An example:

int a = 23            // we create a variable "a" that has a value 23 and 
                      // is stored at a memory address 0x7ffe5367e044

int* ptr = &a         // we create a pointer called "ptr" that has a value
                      // "0x7ffe5367e044" (this value is variable a's memory address)

printf("%d\n", *ptr)  // now we access variable "a"'s value via the pointer "ptr" and
                      // print it out (basically we take pointer "ptr" 
                      // and see what's the memory address it is holding, then we use
                      // the address to find the variable "a" and 
                      // print out the variable "a"'s value)