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?
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.
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.
The asterisk * used to declare a pointer is the same asterisk used for multiplication.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With