#include <stdio.h>
int main() {
int a[3]={1, 2, 3};
int *pointer;
pointer = a; // pointer is address of a[0]
printf("Address of a[0]: %p", pointer);
}
int *pointer
is called the pointer variable, and address of variables can be assigned to this.pointer = a
, the address of a[0]
can be assigning to pointer
.pointer
can be viewed by %p
in the printf
function.0x7ffdfa0e6c7c
, this is the address of a[0]
.#include <stdio.h>
int main() {
int a[3]={1, 2, 3};
int *pointer;
pointer = a; // pointer is address of a[0]
printf("Address of a[0]: %p \n", pointer);
pointer = pointer + 1; // p is address of a[1]
printf("Address of a[1]: %p", pointer);
}
pointer = pointer + 1
represents increment of the pointer variable pointer
.pointer
is the addoress of a[0]
, pointer = pointer + 1
is the address of a[1]
.a[2]
by using increment pointer pointer = pointer + 1
.#include <stdio.h>
int main() {
int a[3]={1, 2, 3};
int *pointer;
pointer = a; // pointer is address of a[0]
// [*pointer] and a[0] are same.
printf("value of a[0]: %d \n", a[0]); // a[0]
printf("value of a[0]: %d \n", *pointer); // *pointer is a[0]
}
*
symbol to a pointer variable, e.g., *pointer
, we can access the original variable a[0]
.pointer
is the address of a[0]
, *pointer
is same as a[0]
.*pointer
and a[0]
is same.a[1]
and a[2]
via pointer variable (use increment pointer pointer = pointer + 1
).#include <stdio.h>
int main() {
int a[3]={1, 2, 3};
int *pointer;
pointer = a;
// before changing value
printf("Value of a[0]: %d \n", a[0]);
// after changing value
*pointer = 30;
printf("Value of a[0]: %d", a[0]);
}
pointer
is the address of a[0]
, *pointer = 30
and a[0] = 30
are same meaning.a[1]
and a[2]
by using pointer = pointer + 1
and *pointer = X
. Not use direct assignment, e.g., a[1] = 10
.for
loop statement and pointer
.#include <stdio.h>
#define MAX_ARR 3
int main() {
int a[3]={1, 2, 3};
int *pointer;
pointer = a; // pointer is address of a[0]
// change value a[0], a[1], a[2] via pointer
for(int i = 0; i < MAX_ARR; i++){
*pointer = (i+1)*10;
pointer = pointer + 1;
}
// view
for(int i = 0; i < MAX_ARR; i++){
printf("a[%d] = %d \n", i, a[i]);
}
}
We can assign valuest to a[0]
, a[1]
and a[2]
by using pointer = pointer + 1
and for` loop statement.
for(int i = 0; i < MAX_ARR; i++)
,i = 0
then *pointer = (0+1)*10;
-> a[0] = 10
i = 1
then *pointer = (1+1)*10;
-> a[1] = 20
i = 2
then *pointer = (2+1)*10;
-> a[2] = 30
#include <stdio.h>
#define MAX_ARR 3
// user-difined function for changing array val.
void change_arr_val(int *pointer){
for(int i = 0; i < MAX_ARR; i++){
*pointer = (i+1)*10;
pointer = pointer + 1;
}
}
int main() {
int a[MAX_ARR]={1, 2, 3};
// change value a[0], a[1], a[2] via pointer
change_arr_val(a);
// view
for(int i = 0; i < MAX_ARR; i++){
printf("a[%d] = %d \n", i, a[i]);
}
}
change_arr_val
is the pointer variable int *pointer
.change_arr_val
by *pointer
.change_arr_val
does not have return
, it is the void
-type function.a = {1, 2, 3}
, output is a = {0, 0, 0}
.