I believe I understand how normal variables and pointers are represented in memory if you are using C.
For example, it’s easy to understand that a pointer Ptr will have an address, and its value will be a different address, which is the space in memory it’s pointing to. The following code:
int main(){
int x = 10;
int *Ptr;
Ptr = &x;
return 0;
}
Would have the following representation in memory:
+---------------------+-------------+---------+
| Variable Name | Address | Value |
+---------------------+-------------+---------+
| x | 3342 | 10 |
+---------------------+-------------+---------+
| Ptr | 5466 | 3342 |
+---------------------+-------------+---------+
However I find it difficult to understand how arrays are represented in memory. For example the code:
int main(){
int x[5];
x[0]=12;
x[1]=13;
x[2]=14;
printf("%p\n",(void*)x);
printf("%p\n",(void*)&x);
return 0;
}
outputs the same address twice (for the sake of simplicity 10568). Meaning that x==&x. Yet *x (or x[0] in array notation) is equal to 12, *(x+1) (or x[1] in array notation) is equal to 13 and so on. How can this be represented? One way could be this:
+---------------------+-------------+----------+----------------------+
| Variable Name | Address | Value | Value IF array |
+---------------------+-------------+----------+----------------------+
| x | 10568 | 10568 | 12 |
+---------------------+-------------+----------+----------------------+
| | 10572 | | 13 |
+---------------------+-------------+----------+----------------------+
| | 10576 | | 14 |
+---------------------+-------------+----------+----------------------+
| | 10580 | | trash |
+---------------------+-------------+----------+----------------------+
| | 10584 | | trash |
+---------------------+-------------+----------+----------------------+
Is this close to what happens, or completely off?
An array is a block of contiguous objects with no spaces in between. This means that
xin your second example is represented in memory as:That is,
xis fiveints big, and has a single address.The weird part about arrays isn’t in how they’re stored – it’s how they’re evaluated in expressions. If you use an array name somewhere that it isn’t the subject of the unary
&orsizeofoperators, it evaluates to the address of its first member.That is, if you just write
x, you will get a value 10568 with typeint *.If, on the other hand you write
&x, then the special rule doesn’t apply – so the&operator works like it normally does, which means that it fetches the address of the array. In the example, this will be a value 10568 with typeint (*)[5].The reason that
x == &xis that the address of the first member of an array is necessarily equal to the address of the array itself, since an array starts with its first member.