In your program there's an only on small mistake in function f(int a[])
void f(int a[]) {
printf("2.%x ", &a);
}
Function f
returns the address of an argument to a function, not an address that it points to.
Since mastering pointers in C is understanding one of the essential aspects of, not only
of C language itself, but machine architecture and basics of CPU/memory functionality.
So, making errors in pointer arithmetic and searching/debugging them can drive even
experienced C programmer mad, it's no surprise that they are harnessed in C++ with
static_cast, dynamic_cast keywords and completely removed (hidden, that is..) in computer languages that followed them after.
So, I went a little further and reworked your code explaining that error better.
#include <stdio.h>
void f(int b[]) {
printf("\n func call. print address: %x", &b); }
void f2(int b[]) {
printf("\n func call. print address(2): %x", b); }
int main()
{
int *j, a[11];
j = a; // load address of 'a' array to int pointer 'j'
// pointer 'j'
// j = address of an array 'a'
// &j = address of 'j' !!
*j = 1; // value of any 'int' that 'j'
// points to is 1,so the value
// of a[0]= 1
// ______ print values of 'j', 'a' ______
// value is from address 'a'
printf("\n1.) value of number (j)= %d", *j);
// int value of address 'a'
printf("\n1.) value of number (a)= %d", a[0]);
// ______ print addresses of 'j', 'a' ______
// address of int variable 'j' that
// holds pointer to 'a'
printf("\n\n2.) addr of number (j)= %x", &j);
// address of 'a' array
printf("\n2.) addr of number (a)= %x", &a);
// ______ all of following adressess are the same ______
// actual pointer (points to 'a' now)
printf("\n\n3.) addr of 'j' = %x", j);
// address od an array 'a'
printf("\n3.) addr of 'a' = %x", a);
// address of first int member in array a
printf("\n3.) addr of 'a[0]'= %x\n", &a[0]);
// ______ print them from function ______ (yours) ..
f(&j); f(a); // outputs an address of an argument passed to a function !!!
// ______ print them from function ______ (changed) ..
f2(&j); f2(a); // outputs an address that an argument points to !!
// (holds address of)
return 0;
}
That int b[]
in functions f
and f2
are written purposely instead of int a[]
so that is clear that argument is a copy of a variable pushed on stack - not an actual variable a
.
Program outputs:
1.) value of number (j)= 1
1.) value of number (a)= 1
2.) addr of number (j)= 5f826328
2.) addr of number (a)= 5f826330
3.) addr of 'j' = 5f826330
3.) addr of 'a' = 5f826330
3.) addr of 'a[0]'= 5f826330
func call. print address: 5f826308
func call. print address: 5f826308
func call. print address(2): 5f826328
func call. print address(2): 5f826330