Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Pointers
Arghya Sahoo
Arghya Sahoo

Posted on

     

Pointers

One of the fundamental concepts in computer programming is avariable. If you are studying computer science, or programming in general, chances are you know what a variable is. In simple terms,

A variable is a container which holds a value

A variable can hold values of certain datatypes, such asint,char,float,bool etc.Pointers are nothing but a special kind of variable. Instead of storing a value, it stores address of a variable.

In case all of this jargon didn't make any sense, we will dig deeper into this.

A computer primarily consists of two types of storage,Primary Memory andSecondary Memory, whenever we execute a program, all of the variables declared in it gets stored in the Primary Memory a.k.a the Main Memory a.k.a theRAM. Now the variables can be anywhere in the RAM, but how could we locate them?

Lets say, you want to invite one of buddies to your house, but he has never visited your house before, then how would he find it? He will need an address. With an address he can locate your house exactly. But without one, he has to roam around the entire world until he finds your house. That doesn't sound like a fun task...does it?

Similarly, every variable that is stored in the primary memory has a specificaddress assigned to it. Different variables can not reside in the same address. Just like, the address of your house and your friends house can not be same unless you both live in the same house.

Now you need to send your address to your friend. How would you do that? Let's say, your send a text message to your friend containing your address. your friend receives it, and comes to your place by locating the address and making his way to it.

Let's retrace his steps, first he receives the text message, which reveals your address, then he locates the specific address to find your house. This is an example of a pointer. Just like the text message contained the address of your house, a pointer contains the address of a variable.It does not contain the actual value of the variable, rather an address where to find it. Imagine if your text message contained your entire house in it. As the text message contained a reference to your actual house, a pointer contains a reference to an actual variable. Dereferencing the pointer reveals the value of the variable it is referencing.

Meme

Let's talk CODE 👨‍💻

  • In C Language, a pointer is declared as*<pointer_var_name> likeint *p;
  • The datatype of a pointer is same as the datatype of the variable it is storing. If a pointer referencing a variable which is storing integer value, the pointer will be an integer pointer, if the variable is storing a character, the pointer will be called a character pointer.

For example

inta=5;int*ip=&a;// '&' is called the "address of" operator, and the '*' is known as "dereference" operator Here, the address of a is fetched and stored inside ipcharc='c';char*cp=&c;
Enter fullscreen modeExit fullscreen mode

Let's dig deeper into the code. For the first example, let the assume thata is stored in memory location100.a has a value of5 andip contains the address ofa. So, technically the value ofip will be 100. Dereferencingip will result in the value ofa which is5.

Single Pointer

Pointers can also hold address of another pointer. They are calleddouble pointers

inta=5;int*ip=&a;// ip holds the address of aint**pp=&p;// pp holds the address of p, which holds the address of a
Enter fullscreen modeExit fullscreen mode

In the above example, dereferencingip once gives the value ofa. As it directly points toa, but in case ofpp to get the value ofa you need to dereference twice. As,pp is holding the address ofip andip is holding the address ofa.

Double Pointer

This way, pointers can be chained together.

Pointers are SLOW! 🐌

Whenever you execute a program, all the variables declared in it is stored in that programs stack frame which resides in RAM. Now, during the calculations, CPU fetches variables from the RAM into its internal registers. This memory access is not the fastest thing in the world. This process takes up quite a few nanoseconds. So, in case of directly accessing a variable, CPU needs to fetch the variable only once from the memory and it gets its value. But in case of pointers, multiple trips are required to the RAM from CPU to get a value. In case of single pointers, first the address of the variable is fetched and then again, the value variable is fetched from that specific memory address. In case of double pointers, it makes three trips to the RAM before it gets the value of the variable. So, longer the chain, the more time it will take to fetch the variable.

Let's take the previous scenario. Instead of providing direct address to your house, you text your friend the address of your local grocery store, there a man hands him the address to your nearest rail station, there someone gives him the address to your house, This will surely take longer time, instead if he was given direct address to your house.

That's all folks, hope this article gives you "yet another" viewpoint towards pointers. Pointers are often misunderstood by a lot of newbie programmers. When broken down to its basics, they are really simple and easy to grasp.

Top comments(5)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
pauljlucas profile image
Paul J. Lucas
C++ Jedi Master
  • Email
  • Location
    San Francisco Bay Area
  • Education
    M.S., University of Illinois at Urbana-Champaign
  • Work
    Retired Principal Software Engineer
  • Joined

Primary Memory and Secondary Memory,

You mention secondary memory, but (1) never say what it is; and (2) never mention it again. So why mention it at all?

Pointers are nothing but a special kind of variable. Instead of storing a value, it stores address of a variable.

No, it simply stores an address. That address doesn't need to belong to a variable:

int *p = malloc( sizeof(int) );
Enter fullscreen modeExit fullscreen mode

Above,p points to anint in memory, but thatint isn't a variable in the same sense asp itself in that it doesn't have name.

Different variables can not reside in the same address.

union U {    int i;    char c;};union U u;
Enter fullscreen modeExit fullscreen mode

Bothu.i andu.c occupy the same address.

In C Language, a pointer is declared as*<pointer_var_name> likeint *p;.

typedef int *pint;pint p;
Enter fullscreen modeExit fullscreen mode

Above,p is declared as a pointer without using*.

Strictly speaking, C's declaration syntax is that you write some base type (likeint), then you write an expression yielding that type. So forint *p, what you're really saying is that the "expression"*p is anintthereforep itself must be a pointer toint. It's declaration by inference.

CollapseExpand
 
arghyasahoo profile image
Arghya Sahoo
  • Location
    Kolkata, India
  • Education
    Techno International Newtown
  • Work
    Student
  • Joined
• Edited on• Edited

This article is written keeping beginners in mind. C can be very complex at times. So to keep things simple, I did skip a lot of stuff and focused only in bare basics. None the less, I find your comment extremely helpful and informative.

CollapseExpand
 
pauljlucas profile image
Paul J. Lucas
C++ Jedi Master
  • Email
  • Location
    San Francisco Bay Area
  • Education
    M.S., University of Illinois at Urbana-Champaign
  • Work
    Retired Principal Software Engineer
  • Joined

This article is written keeping beginners in mind.

I know.

So to keep things simple, I did skip a lot of stuff and focused only in bare basics.

You canboth keep things simpleand correct. They're not mutually exclusive. For example, I would describe a variable as:

Avariable is named and typed region of memory. For example:

int n;

sets aside a region of memory for an integer and makes it accessible using the namen.

I would describe a pointer declaration as:

The C language has a curiously (and some would say confusingly) unique way of declaring variables:

T expression;

that is you write some base typeT, likeint,char, etc., followed by an expression that yields a value of the typeT. To declare a pointer, you would write something like:

int *p;

that is the ultimate type isint followed by*p which an expression thatdereferences (gets the pointed-to value of)p — which meansp therefore must be a pointer toint.

The other way to write simple posts is to say something, but include a note saying that the thing you just said isn't strictly true, but will do for now.

CollapseExpand
 
arunavas profile image
Arunava Saha
  • Joined

Great explanation and in-detail 👍🏻

CollapseExpand
 
pauljlucas profile image
Paul J. Lucas
C++ Jedi Master
  • Email
  • Location
    San Francisco Bay Area
  • Education
    M.S., University of Illinois at Urbana-Champaign
  • Work
    Retired Principal Software Engineer
  • Joined

By the way:

But in case of pointers, multiple trips are required to the RAM from CPU to get a value.

That's simply not true. For example, considerthis. Even though*p is in a loop, the compiler reads the valueonce and is clever enough to convert the loop into a multiplication. Even in a simpler case like:

int n = *p;n += *p;
Enter fullscreen modeExit fullscreen mode

the compiler willstill read from*p only once because itassumes that there are no data races. (If your program is single-threaded, then therecan't be any data races; if your program is multi-threaded and thereare data races, then your program has undefined behavior and the compiler isn't responsible.)

I don't know where you got the idea that reading from a pointerrequires multiple trips to RAM; but in the future, I respectfully suggest that perhaps you should really be 100% sure about a topic before writing about it and spreading incorrect information.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Kolkata, India
  • Education
    Techno International Newtown
  • Work
    Student
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp