idknuttin wrote: |
---|
are they officially called sequences |
No, it appears to be somebody's invented terminology.
Your first example works with an array of four integers that is allocated on the stack (formally, "automatic"). It is passed to the function as a pointer to the first element of the array.
Your second example works with an array of four integers that is allocated on the heap (formally, "dynamic"). It is passed to the function as a pointer to a pointer to the first element of the array. It also has a memory leak.
idknuttin wrote: |
---|
Why do the the integers in the array change values in the first code when I am not passing by reference (not doing void changeArray(int &arr[])) or declaring the array as a pointer? |
It is a confusing feature of C's function declaration that C++ inherited: functions that take arrays by value do not exist. But instead of making the declaration
void changeArray(int arr[])
an error, it is re-written, before the compiler gets to see it, into a *different* declaration:
void changeArray(int* arr)
. Your first function has nothing to do with arrays. It takes a pointer to int. (the code inside the function then assumes that pointer happens to point to an element of an array)
You can observe that if you attempt to also define a function called
void changeArray(int* arr)
later in the program and the compiler will tell you you already defined this one, something like
1 2 3 4 5 6 7
|
main.cpp: In function 'void changeArray(int*)':
main.cpp:10:6: error: redefinition of 'void changeArray(int*)'
void changeArray(int* arr){
^~~~~~~~~~~
main.cpp:3:6: note: 'void changeArray(int*)' previously defined here
void changeArray(int arr[]){
^~~~~~~~~~~
|
At the call site,
changeArray(arrayX);
is attempting to use an array where arrays are not allowed, but pointers are, and the compiler inserts an implicit conversion that constructs a pointer. It is as if you wrote
changeArray(&arrayX[0]);
.
In order to declare a function that takes an array by reference you have to write
void changeArray(int (&arr)[4])
, but that's probably distracting at this point.
Inside the changeArray function in the second piece of code is there a way to write *pX[2]=7 instead of what I have written *(*pX+2)=7 ? |
Yes, the syntax is
(*pX)[2]=7;
.
You can also use your first function with the array from the second example, call it the same way,
changeArray(arrayX);
(this time there will be no conversion since second example's "arrayX" is a pointer, not an array)
oh, and
jonnin wrote: |
---|
arrays are pointers |
No, not at all.