Pointers in C(Value of a pointer)? - c

C Language:
If (p) is a pointer declared as follows:
int a=5, *p;
p = &a;
What does *p will print?

*p won't "print" anything; that's just an expression that de-references the pointer, and produces whatever int value it points at.
You can print it with:
printf("*p=%d\n", *p);
and it will print 5 in your program since p points at a, and the value of a is 5.
The %d is important, it tells printf() to expect an int value, and to format that into a string for printing.
You can also print the pointer itself:
printf("p is %p, a is at %p\n", p, (void *) &a);
this will print the same address twice. The %p format specifier is used for printing addresses.

p is a pointer pointing to an int, *p will be the value of the variable. In this case a. Just for simplicity, you can think of & as the address of, * as the content of pointer as this post The 5-minute Guide to C Pointers points out.
remember a and p are only names, they stands for a variable. Assume the address of a is 1024(which is hardly the real case). Their relation is illustrated as below. The value of a is 5 , When we use p = &a, we assign the address of a, which is 1024 to p. *p will retrieves the value of the address p pointer to, which is what you're looking for: 5.
pic http://cizixs.u.qiniudn.com/pointer
If you want to print the vale, #unwind gives the answer.
Here is a tutorial that might clarify c pointer for you.

p is a pointer to an int. That means it can point to an address, in which an int will be stored.
Writing
p = &a
you set the pointer to point in the address in which integer a is stored.
When you try to print *p, you will get the value that is stored in the address that pointer p points. So you will get 5.
Keep in mind that operator & returns the address of a variable. So &a will return the address of the variable a . Also, when you want to get the value of the variable that is stored in address, if you have a pointer who points ins this address, you use the dereference operator, *. Hence, *p returns the value that is stored in the address that p points to.

p = &a;
p is pointer to a. i.e p holds address of a. and
*p
will give value of a. as & is used to get the address of a variable, * is used for dereferencing a pointer i.e. to get the value of the variable to which the pointer points.

Related

Can I dereference the address of an integer pointer?

I am trying to figure out all the possible ways I could fill in int pointer k considering the following givens:
int i = 40;
int *p = &i;
int *k = ___;
So far I came up with "&i" and "p". However, is it possible to fill in the blank with "*&p" or "&*p"?
My understanding of "*&p" is that it is dereferencing the address of an integer pointer. Which to me means if printed out would output the content of p, which is &i. Or is that not possible when initializing an int pointer? Or is it even possible at all anytime?
I understand "&*p" as the memory address of the integer *p points to. This one I am really unsure about also.
If anyone has any recommendations or suggestions I will greatly appreciate it! Really trying to understand pointers better.
Pointer Basics
A pointer is simply a normal variable that holds the address of something else as its value. In other words, a pointer points to the address where something else can be found. Where you normally think of a variable holding an immediate values, such as int i = 40;, a pointer (e.g. int *p = &i;) would simply hold the address where 40 is stored in memory.
If you need the value stored at the memory address p points to, you dereference p using the unary '*' operator, e.g. int j = *p; will initialize j = 40).
Since p points to the address where 40 is stored, if you change that value at that address (e.g. *p = 41;) 41 is now stored at the address where 40 was before. Since p points to the address of i and you have changed the value at that address, i now equals 41. However j resides in another memory location and its value was set before you changed the value at the address for i, the value for j remains 40.
If you want to create a second pointer (e.g. int *k;) you are just creating another variable that holds an address as its value. If you want k to reference the same address held by p as its value, you simply initialize k the same way you woul intialize any other varaible by assigning its value when it is declared, e.g. int *k = p; (which is the same as assigning k = p; at some point after initialization).
Pointer Arithmetic
Pointer arithmetic works the same way regardless of the type of object pointed to because the type of the pointer controls the pointer arithmetic, e.g. with a char * pointer, pointer+1 points to the next byte (next char), for an int * pointer (normal 4-byte integer), pointer+1 will point to the next int at an offset 4-bytes after pointer. (so a pointer, is just a pointer.... where arithmetic is automatically handled by the type)
Chaining & and * Together
The operators available to take the address of an object and dereference pointers are the unary '&' (address of) operator and the unary '*' (dereference) operator. '&' in taking the address of an object adds one level of indirection. '*' in dereferening a pointer to get the value (or thing) pointed to by the pointer removes one level of indirection. So as #KamilCuk explained in example in his comment it does not matter how many times you apply one after the other, one simply adds and the other removes a level of indirection making all but the final operator superfluous.
(note: when dealing with an array-of-pointers, the postfix [..] operator used to obtain the pointer at an index of the array also acts to derefernce the array of pointers removing one level of indirection)
Your Options
Given your declarations:
int i = 40;
int *p = &i;
int *k = ___;
and the pointer summary above, you have two options, both are equivalent. You can either initialize the pointer k with the address of i directly, e.g.
int *k = &i;
or you can initialize k by assinging the address held by p, e.g.
int *k = p;
Either way, k now holds, as its value, the memory location for i where 40 is currently stored.
I am a little bit unsure what you're trying to do but,
int* p = &i;
now, saying &*p is really just like saying p since this gives you the address.
Just that p is much clearer.
The rule is (quoting C11 standard footnote 102) that for any pointer E
&*E is equivalent to E
You can have as many &*&*&*... in front of any pointer type variable that is on the right side of =.
With the &*&*&* sequence below I denote: zero or more &* sequences. I've put a space after it so it's, like, somehow visible. So: we can assign pointer k to the address of i:
int *k = &*&*&* &i;
and assign k to the same value as p has:
int *k = &*&*&* p;
We can also take the address of pointer p, so do &p, it will have int** - ie. it will be a pointer to a pointer to int. And then we can dereference that address. So *&p. It will be always equal to p.
int *k = &*&*&* *&p;
is it possible to fill in the blank with "*&p" or "&*p"?
Yes, both are correct. The *&p first takes the address of p variables then deferences it, as I said above. The *&variable should be always equal to the value of variable. The second &*p is equal to p.
My understanding of "*&p" is that it is dereferencing the address of an integer pointer. Which to me means if printed out would output the content of p, which is &i. Or is that not possible when initializing an int pointer? Or is it even possible at all anytime?
Yes and yes. It is possible, anytime, with any type. The &* is possible with complete types only.
Side note: It's get really funny with functions. The dereference operator * is ignored in front of a function or a function pointer. This is just a rule in C. See ex. this question. You can have a infinite sequence of * and & in front of a function or a function pointer as long as there are no && sequences in it. It gets ridiculous:
void func(void);
void (*funcptr)(void) = ***&***********&*&*&*&****func;
void (*funcptr2)(void) = ***&***&***&***&***&*******&******&**funcptr;
Both funcptr and funcptr2 are assigned the same value and both point to function func.

Obtaining address of pointer in C with and without ampersand, what's the difference?

I am having difficulty understanding this guide's code on pointers in C. I thought that you needed an ampersand to reference the address of a pointer, but the guide's code manages to obtain it without one. I modified their code with one change which I've commented as"MY ADDED LINE". That line is identical to the line above it, but with the inclusion of an ampersand. The evaluations of these lines produce very similar values, but not identical values. Where is my logic going south?
Thanks,
Nakul
#include <stdio.h>
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* MY ADDED LINE: address stored in pointer variable */
printf("Address stored in ip variable: %x\n", &ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
A pointer is simply a normal variable that holds the address of something else as its value. In other words, a pointer points to the address where something else can be found. Where you normally think of a variable holding an immediate values, such as int a = 5;, a pointer would simply hold the address where 5 is stored in memory, e.g. int *b = &a;.
Being a normal variable, a pointer itself has an address. It's address is the address for the variable itself, not the address it stores. For example, char buf[] = "foo", *p = buf; creates an array buf and assigns the address for the first character in buf as the address held by p (e.g. p points to the first character in buf). But p itself has an address in memory. It is at the address for p where the address for the first character in buf is held in memory. A short example may help:
#include <stdio.h>
int main (void) {
char buf[] = "foo",
*p = buf;
printf ("address for buf : %p\n"
"address of 1st char : %p\n"
"address held by p : %p\n"
"address for p itself : %p\n",
(void*)buf, (void*)&buf[0], (void*)p, (void*)&p);
}
Example Use/Output
$ ./bin/pointeraddr
address for buf : 0x7fffbfd0e530
address of 1st char : 0x7fffbfd0e530
address held by p : 0x7fffbfd0e530
address for p itself : 0x7fffbfd0e540
Now let's look closer at what a pointer holds and the pointer address (where what the pointer holds is held in memory) Let's just use the last three numbers in the addresses for simplicity.
Where is the array of char buf stored in memory?
+---+---+---+---+
| f | o | o | \0| buf - array of char
+---+---+---+---+
5 5 5 5
3 3 3 3
0 1 2 3
When accessing an array, the array is converted to a pointer to the first element subject to the following:
(p3) Except when it is the operand of the sizeof operator, the
_Alignof operator, or the unary '&' operator, or is a string
literal used to initialize an array, an expression that has type
"array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is
not an lvalue.
C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)
What is the first character in the array buf? (answer: buf[0]) What is the address of the first character (using the unary '&' operator)? It is the same as the address of buf, but has the type pointer to char (as apposed to buf which on access is a pointer to array of char[4])
What about p? It has its own address where the address to the first character in buf is stored, e.g.
+---+ p - pointer to char
| 5 |
| 3 | holds the address 0x7fffbfd0e530
| 0 |
+---+
5
4 stored at 0x7fffbfd0e540
0
How do you get the value (character) at the address held by p? You use the unary dereference operator *p. How do you get the address held by p? p is already a pointer, so simply evaluating p itself gives the address held by p, e.g.
char *q = p;
q now holds the address held by p stored at the new address where q is created in memory.
Or, very simply, to print the address held by p now also held by q, simply cast p (or q) to (void*) and print with the "%p" conversion specifier, e.g.
printf ("address held by p & q : %p\n", (void*)p);
No magic. A pointer is simply a variable that holds the address of something else as its value. As with any variable, it has an address all its own. If you think about it that way, you can always figure out what you have -- and what you need to do to get the value stored at that address.
Look things over and let me know if you have further questions.
The logic goes south because "&" gives you a pointer (in your case a pointer to the pointer). Let me adjust your code with the correct terminology, then it should become clear:
printf("Address stored in ip variable, pointing to
the memory location of var: %x\n", ip );
printf("Address pointing to the (memory location / address)
of pointer ip which itself contains the (memory location /
address) of var: %x\n", &ip );
you used
int var = 20;
int *ip;
ip = &var;
and you printed &var, ip, &ip *ip
Here &var and ip will indicate the address of the memory where 20 is saved.
And *ip will indicate the value 20.
And the most important thing what you wanted is &ip.
When int *ip is called, the memory region for this variable will be created.
so ip occupy some memory region.
When you print &ip, then this will indicate the memory address where ip(contains the address of var) is saved.

How to evaluate double pointers in c?

I am learning c, and I am quite confused about this double pointer question.
int x = 44;
int *p = &x;
int **t = &p;
bool a = (*t = &x);
I need to tell whether a will be true or false, and the correct answer is true. My thoughts were that t points to the address of p, and p points to the address of x. I know if you put **t, it should point to the address of x, but I thought if you just put *t it should point to the address of p. Can anyone explain?
int x = 44;
Declares integer variable x, which stores value of 44.
int *p = &x;
Declares integer pointer variable called p, p now stores the address of x.
int **t = &p;
Declares pointer to pointer of type int called t, t stores the address of p. (Pointers have addresses too)
bool a = (*t = &x);
In C;
'*' = Extracts the value from an address (Dereference)
'&' = Gives address of variable (Reference)
Since t is a pointer to the value stored in p. *t will be the value stored in p, which is the address of x. (We figured this out in the second line)
On the other hand since the & is used on variable x. This will extract the address of x.
Therefore *t == &x, which sets the boolean value a to true.
I know if you put **t, it should point to the address of x, but I thought if you just put *t it should point to the address of p.
Well, that is both right and wrong. The "point to the address of" should read "designate" and it is right.
First of all, you declared 3 variables
int x = 42;
int *p = &x;
int **t = &p;
Now this could be read as x is an int, *p is an int and **t is an int. Then we initialize x to value 42, then p to address of x, and t to address of p.
Given
int *p = &x;
the two L-value expressions x and *p not only are both of type int, and have the same value; they designate the same object. Just like 10565305 and Amy Finck designate the same user. This is also called aliasing - *p aliases x, just like Amy Fink and User 10565305 are your aliases on Stack Overflow (and the name x is not the object itself, just like you're a person, not a name).
Likewise with int **t = &p, we now notice that just like above, *t and p designate the same object, p. And ps current value is that of expression &x. Hence *t == &x must be true.
As for *ts type, if **t is an int, then *t must be int * (the law of conservation of stars in pointers ;) which of course matches the type of p, and type of &x.
It will be true. Here is the explanation:
In bool a = (*t = &x); the variable t holds address of p. You are de-referencing t i.e *t will point to the content stored in location of p.
The content stored in address of p is address of x. Remember *p = &x. Comparing *t == &x will then be true.
In the question you have mentioned *t = &x, if that is the original code it is still true, as assignment in (*t = &x); returns a non-null pointer. When that non-null pointer is converted to a boolean, it becomes true.
The first line declares a variable 'x' of type 'int', and assigns the numeric literal value 44 to that variable.
int x = 44;
The next line (2) declares a variable 'p' of type 'pointer to int', and assigns the value of the expression '&x' (which is the address of x, a pointer to int),
int *p = &x;
The next line (3) declares a variable 't' of type 'pointer to, pointer to int' (a pointer that contains a pointer to an int type), and assigns the expression '&p' (which is the address of p, a pointer to int,
int **t = &p;
The variable t is a 'doubly-indirected pointer'.
Now comes the 'tricky part'.
The next line (4) declares a variable 'a' which is a bool(ean) variable (true/false), and assigns the value of the expression on the rhs (right hand side, '(*t = &x)'. The parenthesis are there to ensure the intended order of precedence is observed. So we evaluate the expression '*t = &x'.
bool a = (*t = &x);
Here is the 'tricky' part, the code provided has an assignment '=' operator! If this were comparison, then the '==' operator would appear. So this statement takes the address of x (pointer to int), and stores it into *t (the location pointed at by t, and that location is a pointer to int).
Were this comparison, the expression would compare the same values, and would be true. But this is assignment. And an assignment expression returns the value assigned, which is the address of x (pointer to x). On most systems, that pointer is a location in memory (and could only be zero(NULL) if the variable were stored at the zero address).
The expression is of type 'pointer to int', but is converted (cast) to type bool. Since C considers false=0 and true anything not equal to 0, the value is converted from (likely not NULL) pointer to int to bool (true).
Had the parenthesis been omitted, then the assignment would still occur (right to left order of evaluation for assignment operator), but then the cast would occur. But remove the parenthesis, compile it and see what your compiler says.
You said:
I need to tell whether a will be true or false, and the correct answer is true. My thoughts were that t points to the address of p, and p points to the address of x. I know if you put **t, it should point to the address of x, but I thought if you just put *t it should point to the address of p. Can anyone explain?
Here is my attempt an an explanation:
The bold part is where you are confused. **t == x == *p, and *t == &x == p.
**t references the value stored in at x's address, not the address itself.
*t =p references the address of x, and dereferencing either of them give you the value of x.
Does this explanation clear things up? I can expand or make a sample program if it helps.
sample scratch code would be to printf these values to gain clarity:
int x = 42; //&x = 0x1234DEAD (or some other address, just picked one for an example)
int * p = &x; // p = 0x1234DEAD and &p = 0x5678BEEF (agian an example address)
int **t = &p; // t = 0x5678BEEF
printf("%d and %d and %d\n",**t, *p, x); //should be 42;
printf("%p and %p\n",*t, p); //should be 0x1234DEAD;
printf("%p\n",t); //should be 0x5678BEEF;
My thoughts were that t points to the address of p
Yes.
and p points to the address of x
Yes.
I know if you put **t, it should point to the address of x
No, **t is x.
but I thought if you just put *t it should point to the address of p.
No, *t is p.
The dereference operator "gives you" the pointed-to thing. Hence, since, p is also &x (because that's what you set it to), *t == &x.
It's moot though because you didn't actually compare with ==, you assigned with =, so your expression evaluates to the result of that assignment, which is &x, which is a non-NULL pointer, so the whole thing is "true-like". (Only a null pointer converts to false).

Difference between **ptr and &ptr

According to my knowledge
**ptr = the address of memory location of the pointer variable ptr
&ptr = the address of memory location where the value of ptr is stored.
Am I correct or **ptr == &ptr?
If they are equal whether I can pass &ptr as a pass by address for a function as a replacement to ptr? Knowledge me on this.
It might help if you understand that for any pointer (or array) p and index i the expression *(p + i) is equivalent to p[i].
Now if i is zero that means we have *(p + 0) which is equal to *p, and its equivalent expression p[0]. That means when you do dereference a pointer you get the value of where it points.
Double-dereferencing a pointer only works if the pointer is pointing to another pointer.
You understanding of the address-of operator & is correct though.
Lets work on an example:
int a = 10;
int *p = &a; // Makes p point to the variable a
int **pp = &p; // Makes pp point to the variable p
Now if we do *pp we get the pointer p, and if we to **pp we get the variable a and its value.
printf("Value of a is %d\n", a); // Will print "Value of a is 10\n"
printf("Value of *p is %d\n", *p); // Will print "Value of *p is 10\n"
printf("Value of **pp is %d\n", **pp); // Will print "Value of **pp is 10\n"
Also, using pointer to pointer might seem not very usable, but if you think about dynamically allocated arrays things change. For a dynamically allocated array you need to use a pointer, and if you want a matrix (i.e. an array of arrays) you need to use pointer to pointer, if you want to allocate both "dimensions" dynamically.
Furthermore, while C doesn't support passing arguments by reference, it can be emulated using pointers, and if you need to pass a pointer by reference you do it by passing a pointer to a pointer (using the address-of operator).
Lastly a small fun fact. I started this answer by telling you that *(p + i) and p[i] are equivalent. Because of the commutative property of addition, the expression *(p + i) is equivalent to *(i + p) which means that p[i] is equivalent to i[p]. Don't do it in real code though, it will only obfuscate the code and cause confusion for new readers of the code.
Pay attention to the context: There is a difference when declaring and when using the pointer. In general, & is taking the address and ** is dereferencing the pointer twice. Obviously, these are not the same.
But in variable decfinitions, ** declares a pointer to a pointer. The declared variable can the take the address of a pointer as value:
int d = 10;
int *p = &d;
int **pp = &p;
This still doesn't mean that **p and & are the same: Here, the ** is part of the variable's type: pointer to pointer to int.
The same applies to function argumets: The function
void f(int **p);
takes a pointer to pointer to int as argument and you can pass it the address of a pointer to int.
'*' operator is used to hold a memory address.
'&' operator returns the address at which the variable is held.
for example
int a = 10; (10 is located in memory at, for example, 0xddffff0
int *b = &a; (&a is the same thing as 0xddffff0, so b now points to that address)
So '&' operator returns the address while '*' operator point at the address.
Actually my knowledge on double pointer was wrong .
**ptr - Value of the variable pointed by another pointer or we can say it is a pointer to a pointer
let me clarify with an ex
#include<stdio.h>
int main()
{
int num = 100 , *p , **ptr2ptr ;//Address of num=2000 ,p=3000 ,ptr2ptr=4000
p = &num;
ptr2ptr = &p;
printf("Single pointer *p =%d\n",*p);
printf("Double pointer **ptr2ptr=%d \n", **ptr2ptr);
printf("Address stored in p variable =%d \n", p);
printf("Address of p variable=%d\n", &p);
printf("Address of ptr2ptr=%d", &ptr2ptr);
return(0);
}
Output
Single pointer *p = 100
Double pointer **ptr2ptr= 100
Address stored in p variable =2000
Address of p variable=3000
Address of ptr2ptr=4000
From the above example it is clear **ptr2ptr(100) not equal to &ptr2ptr(4000) .
So I have found answer for my question .

Pointers: a query about pointers

I'm learning C and C#. I'm learning about pointers and don't know what it means to combine the indirection operator and the address operator. What does it mean to combine the two?
Here is an example:
int *p, *q;
p = *&q;
& can be thought of as an address of (<something>) operator. So &q is address of q. Now * can be thought of as an value at (<something>) operator. So *q is basically the value stored at the address contained in q, i.e, * treats the variable as always containing an address. Now *&q, by associativity is *(&q). Which means
value stored at (address of q) which is same as value stored at q
address of q will be having another address since q is a pointer. So it is the same as
p=q
It means what it must mean. :)
If you read it from left to right, the right hand side simply means "the value retreived by following the pointer whose value is the address of q".
It's the same as p = *(&q);, and thus it's the same as p = q;.
I didn't even notice, but your program is wrong to declare p and q to be pointers. That won't compile, it should be:
int p, q;
p = *&q;
Also, this might be a bit ill-defined since q is never assigned a value before being read, not 100% sure about that.
&q;
would give you the address of the variable q, that is it's a pointer to q we could write
int ** pointerToQ = &q;
if we then say
*pointerToQ
we are asking for whater ever pointerToQ points to, which is q itself. So
*&q
Just gets us back to q.
Your example would set pointer p to the value of pointer q. It does nothing to the values pointed by p and q. It just sets the variable p, to the value of variable q, which both happen to be pointers to integer values. Lets see some examples:
*p = *q; // the value at the address pointed by q, gets copied to the address, pointed by p
p = &q; // this is illegal, since the type of &q is int ** (pointer to a pointer to an integer), but the type of p is int *

Resources