Moving Pointer Variable Associated With Array var

Hi all, I'm still a beginner and could you please help me, how does indexing done within pointer variable which points to an array variable. I have a code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <stdio.h>
#include <stdlib.h>

int main()
{
int *bil;
int i;
int arr[] = {2,3,4,5,6,7};

bil = arr; // same with bil = &arr[0]

for(i = 0; i < 6; i++)
{
	*bil = *(bil + 1);
	printf("Bil Modified; %d\n", *bil);
}

printf("\nThe different Incrementing the pointer value with pointer address; \n");

for(i = 0; i < 6; i++)
{
	*bil = *(bil + i);
	printf("Bil Modified; %d\n", *bil);
}

printf("\n");

for(i = 0; i < 6; i++)
{
	*bil = *bil + 1;
	printf("Bil Modified; %d\n", *bil);
}


return 0;
}


The output will look like this


denilugito@linux-mrcm:~/Documents/Project/C++ Code/Kumpulan Source/Coba array> ./coba_lagi 
Bil Modified; 3
Bil Modified; 3
Bil Modified; 3
Bil Modified; 3
Bil Modified; 3
Bil Modified; 3

The different Incrementing the pointer value with pointer address; 
Bil Modified; 3
Bil Modified; 3
Bil Modified; 4
Bil Modified; 5
Bil Modified; 6
Bil Modified; 7

Bil Modified; 8
Bil Modified; 9
Bil Modified; 10
Bil Modified; 11
Bil Modified; 12
Bil Modified; 13


Things that makes me confused a little is that when the second for is encountered the pointer to array variable has pointed to array index 1 (with value 3). But the value of 3 printed two times (for index 0 and 1). And for last for - loop section the array index is incremented even though the one that i incremented is the value (not the pointer address). Why is that??

Thnx before that..
You never really modify the pointers themselves.

*bil = *(bil + 1); bil points to arr[0], so (bil+1) points to arr[1]. This line is equivalent to arr[0] = arr[1]. Note that now arr = 3, 3, 4, 5, 6, 7. Thats why you get 3 in the second loop.

*bil = *(bil + i); this line is the same as arr[0] = arr[i]. After the loop arr = 7, 3, 4, 5, 6, 7.

*bil = *bil + 1; this says arr[0]++.

What were you trying to make?
Topic archived. No new replies allowed.