Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the pointer star * in C?

I'm struggling with the pointer sign *, I find it very confusing in how it's used in both declarations and expressions.

For example:

int *i; // i is a pointer to an int 

But what is the logic behind the syntax? What does the * just before the i mean? Let's take the following example. Please correct me where I'm wrong:

char **s; char *(*s); // added parentheses to highlight precedence 

And this is where I lose track. The *s between the parantheses means: s is a pointer? But a pointer to what? And what does the * outside the parentheses mean: a pointer to what s is pointing?

So the meaning of this is: The pointer pointing to what s is pointing is a pointer to a char?

I'm at a loss. Is the * sign interpreted differently in declarations and expressions? If so, how is it interpreted differently? Where am I going wrong?

like image 964
Jeffrey Avatar asked Mar 30 '11 09:03

Jeffrey


People also ask

What does * in the pointer variable indicates?

The * in the declaration statement is not an operator, but indicates that the. name followed is a pointer variable. For example, int *p1, *p2, i; // p1 and p2 are int pointers. i is an int.

What is star in pointer in C?

The * in expression means "the value stored in the address" so if c is a pointer to some char, then *c is the specific char.

What does the * mean in pointers?

The asterisk * used to declare a pointer is the same asterisk used for multiplication.

What is * in pointers in C?

A pointer is a variable that stores the memory address of another variable as its value. A pointer variable points to a data type (like int ) of the same type, and is created with the * operator.


2 Answers

int i; //i is an int. int *i; //i is a pointer to an int int **i;//i is a pointer to a pointer to an int. 

Is the * sign interpreted differently in declarations and expressions?

Yes. They're completely different. in a declaration * is used to declare pointers. In an expression unary * is used to dereference a pointer (or as the binary multiplication operator)

Some examples:

int i = 10; //i is an int, it has allocated storage to store an int. int *k; // k is an uninitialized pointer to an int.          //It does not store an int, but a pointer to one. k = &i; // make k point to i. We take the address of i and store it in k int j = *k; //here we dereference the k pointer to get at the int value it points             //to. As it points to i, *k will get the value 10 and store it in j 
like image 35
nos Avatar answered Sep 18 '22 04:09

nos


Take it this way:

int *i means the value to which i points is an integer.

char **p means that p is a pointer which is itself a pointer to a char.enter image description here

like image 198
pradeepchhetri Avatar answered Sep 17 '22 04:09

pradeepchhetri