The error in this line of code:
p = &input_line;
Can be resolved by changing it with:
p = input_line;
That's because your're assigning the memory direction of the array.
Its value is a pointer to a char pointer. That's why the error is
raised. Remember, the operator &
gives to you the variables memory
direction.
A pointer stores a memory direction of an object. An array is a sequence of objects by a certain type that are located in consecutives reserved amount of space in memory.
Each index of an array is a number composed of the digits from 0 to 9. Each element of an array is an object that you can take the address of, like a pointer to an object memory location. In an array the objects are located in consecutive memory locations. When you assign an array to a pointer, you're assigning the pointer to the arrays first element, it's array[0]
.
When you increase by 1 the pointer value, the pointer will point to the next object in a memory location. So, arrays and pointers have similar behavior. If you assign to a pointer an array and then you increase by 1 the pointer value, it will point now to the object in the array.
This is not only for char
type, it's for every type in C++. In this page you can get more information about pointers and array. You must note that the pointer and the array must contain or point to the same variable type.
Here's an example from this page:
int* ptr;
int a[5];
ptr = &a[2]; // &a[2] is the address of third element of a[5].
An output example from the example in this page is:
Displaying address using arrays:
&arr[0] = 0x7fff5fbff880
&arr[1] = 0x7fff5fbff884
&arr[2] = 0x7fff5fbff888
&arr[3] = 0x7fff5fbff88c
&arr[4] = 0x7fff5fbff890
Displaying address using pointers:
ptr + 0 = 0x7fff5fbff880
ptr + 1 = 0x7fff5fbff884
ptr + 2 = 0x7fff5fbff888
ptr + 3 = 0x7fff5fbff88c
ptr + 4 = 0x7fff5fbff890
As you can note in the output example, both are pointing to the same memory location, so you can access the objects from both methods.
Formally, in the C++ 11 standard is mentioned that:
Array-to-pointer conversion:
An lvalue or rvalue of type “array
of N
T
” or “array
of
unknown bound of T
” can be converted to a prvalue of type “pointer
to T
”. The result is a pointer to the first element of the array
.
You can see those pages for more information about this theme:
C++ Pointer to an Array.
C++ Pointers and Arrays.
C++ Pointer to an Array.
C++11 Standard Library Extensions