
Untitled
By: a guest on
Jul 1st, 2012 | syntax:
None | size: 1.20 KB | hits: 16 | expires: Never
difference between pointer and reference in c?
address 01 02 03
+----+----+----+...
data within | 23 | 6f | 4a |
+----+----+----+...
char c = 'z'; // 'z' is 7a in hex
address 01 02 03
+----+----+----+...
data within | 7a | 6f | 4a |
+----+----+----+...
char* p = &c; // point at c
address 01 02 03
+----+----+----+...
data within | 7a | 01 | 4a |
+----+----+----+...
char& r = c;
const char& r = c;
r = 'y'; // error; you may not change c through r
c = 'y' // ok. and now r == 'y' as well
| Address | Value |
|----------|----------------|
|0x1111 |0x1112 | <-- Pointer!
|0x1112 |42 | <-- Pointed value
|0x1113 |42 | <-- Some other value
mov rax, [r8]
void add(int* x)
{
*x = *x + 7;
}
void cppadd(int& x)
{
int a = 7;
x = &a; // doesn't work.
}
int a;
int* b = &a;
// b holds the memory address of a, not the value of a.
int a;
int* b = &a;
// b is a reference to a.
int a;
int* b = &a;
int c = *b;
// c dereferences b, meaning that c will be set with the value stored in the address that b contains.