I am now learning about pointers. This is the sample code from a book:
#include <stdio.h>
int main()
{
int i;
char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
int int_array[5] = {1, 2, 3, 4, 5};
char *char_ptr;
int *int_ptr;
char_ptr = char_array;
int_ptr = int_array;
for(i=0; i < 5; i++) {
printf("[integer pointer] points to %p, which contains the integer %d\n", int_ptr, *int_ptr + 1);
int_ptr = int_ptr + 1;
}
for(i=0; i <5; i++) {
printf("[char pointer] points to %p, which contains the char '%c'\n", char_ptr, *char_ptr);
char_ptr = char_ptr + 1;
}
}
Q. Would char *char_ptr = char_array; change how this code functions in any way or is this the same thing as lines shown above?
Q. Other sample codes from this book also assigns &variable to a pointer, which from I understand means to store the address of a variable to that pointer, (e.g. char_ptr = &char_array;). This sample just assigns the variable itself to the pointer, but this program still manages to print the memory addresses that the pointer points to. Why or why not use char_ptr = &char_array; in this context? Or does it not make a difference?
> kingvon@KingVon:~/Desktop/asm$ gcc pointertypes.c
> kingvon@KingVon:~/Desktop/asm$ ./a.out [integer pointer] points to
> 0x7ffc225227a0, which contains the integer 2 [integer pointer] points
> to 0x7ffc225227a4, which contains the integer 3 [integer pointer]
> points to 0x7ffc225227a8, which contains the integer 4 [integer
> pointer] points to 0x7ffc225227ac, which contains the integer 5
> [integer pointer] points to 0x7ffc225227b0, which contains the integer
> 6 [char pointer] points to 0x7ffc225227c3, which contains the char 'a'
> [char pointer] points to 0x7ffc225227c4, which contains the char 'b'
> [char pointer] points to 0x7ffc225227c5, which contains the char 'c'
> [char pointer] points to 0x7ffc225227c6, which contains the char 'd'
> [char pointer] points to 0x7ffc225227c7, which contains the char 'e'
> kingvon@KingVon:~/Desktop/asm$
Edit- typo
int_ptr = int_ptr = 1;and you meanint_ptr = int_ptr + 1;.