Reputation:
When are the pointers to a
and b
created?
In the code below, I only declared/initiated a
and b
.
But the function swap
treats them with &a
and &b
which are pointers.
My question is,
Are the pointers to a and b created at the same time with int a
and int b
?
Or are they created when swap
function was called with arguments &a
and &b
?
#include <stdio.h>
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int a = 3;
int b = 5;
swap(&a, &b);
printf("%d %d", a, b);
}
Upvotes: 2
Views: 123
Reputation: 3229
All variables are stored at addresses in memory. Therefore, there exists a pointer for each variable you declare, even if you do not declare them as pointers. To understand what is actually happening it helps to know the basics of assembly language. The following is the relevant part of your code compiled in x86_64 and viewed via objdump
.
6ee: c7 45 f0 03 00 00 00 mov DWORD PTR [rbp-0x10],0x3
6f5: c7 45 f4 05 00 00 00 mov DWORD PTR [rbp-0xc],0x5
6fc: 48 8d 55 f4 lea rdx,[rbp-0xc]
700: 48 8d 45 f0 lea rax,[rbp-0x10]
704: 48 89 d6 mov rsi,rdx
707: 48 89 c7 mov rdi,rax
70a: e8 9b ff ff ff call 6aa <swap>
At lines 0x6ee and 0x6f5 your variables are initialized. Notice that in this case they are actually stored on the stackframe at rbp-0x10 and rbp-0xc respectively. On the following two lines, the addresses of these variables are stored into registers rdx and rax, respectively, then moved into the appropriate registers (rsi and rdi) so that they can be passed the the swap function.
To summarize, C is written at a higher level than the machine architecture that actually executes your code. In machine languages, variables are stored at locations in memory, which are accessible through pointers in the form of offsets to registers, memory sections, etc. In the example above you can see that the data 3 and 5 were "stored in pointer locations" the entire time.
Upvotes: 1
Reputation: 9619
When you say that a
and b
are created, this essentially means that a chunk of memory is assigned to these variables, which is then initialized with the respective values. Those memory chunks have an address. The pointers in swap()
are nothing but the addresses in memory where a
and b
are stored.
Upvotes: 2
Reputation: 311088
The pointers to a
and b
are created as results of evaluation of argument expressions in the function call
swap(&a, &b);
^^ ^^
From the C Standard (6.5.3.2 Address and indirection operators)
3 The unary & operator yields the address of its operand.
Thus the expressions &a
and &b
have the type int *
and yield the addresses of the variables a
and b
.
Upvotes: 3