DEV Community

Discussion on: Pointers

Collapse
 
pauljlucas profile image
Paul J. Lucas

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 mode Exit fullscreen mode

Above, p points to an int in memory, but that int isn't a variable in the same sense as p 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 mode Exit fullscreen mode

Both u.i and u.c occupy the same address.

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

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

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

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

Collapse
 
arghyasahoo profile image
Arghya Sahoo • 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.

Collapse
 
pauljlucas profile image
Paul J. Lucas

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 can both keep things simple and correct. They're not mutually exclusive. For example, I would describe a variable as:

A variable 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 name n.

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 type T, like int, char, etc., followed by an expression that yields a value of the type T. To declare a pointer, you would write something like:

int *p;

that is the ultimate type is int followed by *p which an expression that dereferences (gets the pointed-to value of) p — which means p therefore must be a pointer to int.

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.