As background, I gave an answer to this post a little while ago:
And it unintentionally kicked off a really long comment chain about pointers vs. arrays in C++ because I tried to oversimplify and I made the statement "arrays are pointers". Though my final answer sounds pretty decent, it was only after some heavy editing in response to a lot of the comments I got.
This question is not meant to be troll bait, I understand that a pointer and an array are not the same thing, but some of the available syntax in the C++ language certainly makes them behave very similarly in a lot of cases. (FYI, my compiler is i686-apple-darwin9-g++-4.0.1 on OS X 10.5.8)
For instance, this code compiles and runs just fine for me (I realize x[8] is a potential segmentation fault):
//this is just a simple pointer
int *x = new int;
cout << x << " " << (*x) << " " << x[8] << endl; //might segfault
//this is a dynamic array
int* y = new int[10];
cout << y << " " << (*y) << " " << y[8] << endl;
//this is a static array
int z[10];
cout << z << " " << (*z) << " " << z[8] << endl;
That particular snippet makes it look like pointers and arrays can be used almost identically, but if I add this to the bottom of that code, the last two lines won't compile:
x = y;
x = z;
y = x;
y = z;
//z = x; //won't compile
//z = y; //won't compile
So clearly the compiler at least understands that z and x are different things, but I can interchange x and y just fine.
This is further confusing when you look at passing arrays to functions and returning arrays from functions. Consider this example (again, I am aware of the potential segmentation faults here when passing x):
void foo(int in[])
{
cout << in[8] << endl;
}
void bar(int* in)
{
cout << in[8] << endl;
}
int main()
{
//this is just a simple pointer
int *x = new int;
foo(x);
bar(x);
//this is a dynamic array
int* y = new int[10];
foo(y);
bar(y);
//this is a static array
int z[10];
foo(z);
bar(z);
}
All this code properly compiles and runs on my machine.
I feel like I have a decent internal understanding of what's going on here, but if you asked me to articulate exactly what's happening, I don't feel like I could satisfactorily explain. So here's what I'm getting at:
When I pass an array to a function as
int* ininstead ofint in[], what am I gaining or losing? Is the same true when returning an array asint*? Are there ever bad side effects from doing this?If I asked you what the data type of
yis, would you say pointer to int, array of ints or something else?Similarly, what happens when I say
x = yvs.x = z? I'm still able to usex[]and access the things that were originally inyorz, but is this really just because pointer arithmetic happens to land me in memory space that is still valid?
I've dug through all the similar array/pointer questions on SO and I'm having trouble finding the definitive explanation that clears this up for me once and for all.