As a general question, can arrays be set to other arrays? For example, this is my code:
1 2 3 4 5 6 7 8 9
// CLASS DEFINITION
class myClass
{
private:
int m_array1[5];
public:
operatorint*();
};
1 2 3 4 5 6
// This is my operator overload
myClass::operatorint*()
{
returnthis->m_array1;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main()
{
myClass g;
for (int i = 0; i < 5; i++)
{
int copyOfIterator = i;
g[i] = ++copyOfIterator;
cout << g[i] << "\n";
}
int* examplePointer1 = g; cout << "examplePointer1's first element is " << examplePointer1[0] << "\n";
int exampleArray1[5]; exampleArray1 = g; cout << "exampleArray1's first element is " << exampleArray1[0] << "\n";
return 0;
}
When I try to set exampleArray1 equal to class 'g', the compiler gives me an error, but when I set the pointer equal to class 'g', the compiler does not error. Why is this? Technically, I am setting a pointer to a pointer in both statements
You can't assign arrays to arrays (let alone assign pointers to arrays). Use std::vector instead.
The reason int* examplePointer1 = g; works is because you have a conversion operator to int*.
So are arrays constant pointers that cannot change address?
No, arrays are arrays like hanst99 said. A group of elements of the same type that are adjacent in memory.
There are C++ arrays (std::array in C++11 or boost::array) that encapsulate normal C arrays and can be used like a normal container (for example, you can assign them and iterate over them).
The title of the thread does not correspond to the discussion. In fact arrays can be set equal each other by copying elements of one array into another.:)
Whether the array is a pointer to the first element or not, as long as its not const, I should be able to change what the pointer pointing to the first element of the array is pointing to.
Arrays can not be assigned. There is no such operation for arrays as the assignment exactly the same way as there is no such operation for example as the comparision (==) for arrays.
It is only then the name of an array takes part in an expression its name converted to a pointer of the first element of the array.
In fact std::array uses the same copying element by element but thsi is done by the compiler when it performs assignment of one structure with the array to another.:)
Well, apparently this page says that an array is a constant pointer.
So it does, but it is incorrect. Don't take anything you read in tutorials at face value, stick to (reputable!) books or refer to the C++ standard directly. The confusion about this usually stems from the fact that an array can be implicitly converted to a pointer.