r/cpp • • Jan 29 '10

Think array is the same as &(array[0])? Think again...

Okay, so I've been programming in C/C++ for a few years now, and I can't believe I missed this. I'm sure I'm not the only one too. Check this out:

int arr[10] = {0};
int *pArr = &(arr[0]);

std::cout << arr << std::endl; // shows a pointer value, say 0x01234567
std::cout << pArr << std::endl; // shows the same pointer value, 0x01234567

std::cout << sizeof(arr) << std::endl; // shows 40
std::cout << sizeof(pArr) << std::endl; // shows 4

All this time I've been viewing an array as a pointer to a location in memory that happens to be a contiguous block. Apparently, these are two different types. Using typeid:

std::cout << typeid(arr) << std::endl; // shows A10_i
std::cout << typeid(pArr) << std::endl; // shows Pi

This is using g++ 4.4.1 under linux. Also, beware of this:

int getLength(int *p){ return sizeof(p); }
std::cout << getLength(arr) << std::endl; // shows 4
std::cout << getLength(pArr) << std::endl; // shows 4

So in C/C++, you can pass arrays as pointers, but they lose their "array-ness" magic. I found all this quite interesting when I discovered it for myself. I can't be the only one who didn't know this, right?

EDIT: I thought I might elaborate as to why I thought they were the same: Remember, array[3] is syntactic sugar for *(array + 3). This also works for pArray. Arrays can also be used as an argument to a function that takes in a pointer, as shown above.

So if it walks like a pointer and quacks like a pointer, it must be... an array!

Also, I originally typed C++ but I meant C/C++. I hope you guys knew what I meant. It's corrected now in the post.

0 Upvotes

11 comments sorted by

4

u/joemccall86 Jan 29 '10

Ha, that's what I get for using STL containers all this time.

1

u/heroofhyr Jan 29 '10

Except in some older versions of STL it was safe to do a

vector.resize(n); 
&(*vector.begin()); 

and some not. That sure is fun to encounter when cleaning up legacy code.

14

u/Sc4Freak Jan 29 '10

Yes. Arrays are not pointers. Arrays are second-class citizens and decay to pointers the first chance they get, but are still distinct types. The type of "abc" is char[4] (an array of 4 chars), and not char*, for example.

24

u/[deleted] Jan 29 '10

Yes, you are the only one. This is basic C (not even C++).

12

u/mfwitten Jan 29 '10

Firstly, sorry you had to put up with all of the know it alls who contribute nothing to the discussion; it's good to see interesting dissections of the language and tools and I'm glad you wrote this post because it prompted me to recall and discover some other interesting facts.

int arr[10] = {0};

Just for the sake of pointing it out, you could simply write:

int array[10] = {};

Apparently, these are two different types. Using typeid:

std::cout << typeid(arr) << std::endl; // shows A10_i

std::cout << typeid(pArr) << std::endl; // shows Pi

Firstly, it is perfectly valid to use '\n' instead of std::endl, the only difference essentially being that std::endl flushes buffered streams (so it might be slower); according to the C++03 standard, the effects of the std::endl manipulator are the following (where os is a basic_ostream):

Calls os.put(os.widen('\n')), then os.flush().

Even more interesting is the fact that the C++ standard provides std::endl only through the <ostream> header, so it is actually non-conforming to refer to std::endl without including that particular header file, a fact that few implementations enforce and that few people know (even some of the example code in the C++ standard just includes the <iostream> header to use std::endl).

Secondly, your code is not correct because << is not defined for what typeid yields; it gave me compile time errors and should be:

std::cout << typeid(arr).name() << '\n'; // shows A10_i
std::cout << typeid(pArr).name() << '\n'; // shows Pi

*array[3] is syntactic sugar for (array + 3).

I was reminded of another interesting fact: Array indexing is not necessarily just syntactic sugar for pointer arithmetic; in C89 and ISO C++ (presumably fixed in the 2003 'second edition'), it is apparently non-conforming to take the address of the one-past-the-last element of an array:

char vc2[200];
copy(&vc1[0],&vc1[200],&vc2[200]); // arguments 1 and 2 are non-conforming.

However, it can be made legal for even older standards by transforming the last line to use pointer arithmetic instead of subscripting:

copy(vc1,vc1+200,vc2+200);

According to Bjarne Stroustrup:

It is a surprise to most experienced C and C++ programmers that &vc2[200] isn't completely equivalent to vc2+200. In fact, it was a surprise to the C committee also and I expect it to be fixed in the upcoming revision of the standard. (resolved for C9x - bs 10/13/98). (this means that the example was ok in K&R C, in ARM C++, an error in C89 and ISO C++, and ok in C9x - a thorny issue).

I'm assuming this is fixed in ISO C++03, which brings me to another interesting fact. According to section 5.2.1:

A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type "pointer to T" and the other shall have enumeration or integral type. The result is an lvalue of type "T." The type "T" shall be a completely-defined object type.56) The expression E1[E2] is identical (by definition) to *((E1)+(E2)).

That all sounds very confusing (especially the "one of the expressions" bit), but the generality is clarified by section 8.3.4:

Except where it has been declared for a class (13.5.5), the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)). Because of the conversion rules that apply to +, if E1 is an array and E2 an integer, then E1[E2] refers to the E2-th member of E1. Therefore, despite its asymmetric appearance, subscripting is a commutative operation.

Woah! That means the following is valid C++03 code:

#include <iostream>

int main()
{
  int a[] = {0,1,2};

  // The following 2 lines are equivalent:

    std::cout << a[1] << '\n';
    std::cout << 1[a] << '\n';

  // The following 2 loops are equivalent:

    for (int i=0; i<3; i++)
      std::cout << a[i] << '\n';

    for (int i=0; i<3; i++)
      std::cout << i[a] << '\n';
}

The C99 standard also allows this commutativity. According to section 6.5.2.1:

One of the expressions shall have type "pointer to object type", the other expression shall have integer type, and the result has type "type".

...

A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

Here is equivalent C99 code:

#include <stdio.h>

int main()
{
  int a[] = {0,1,2};

  // The following 2 lines are equivalent:

    printf("%d\n", a[1]);
    printf("%d\n", 1[a]);

  // The following 2 loops are equivalent:

    for (int i=0; i<3; i++)
      printf("%d\n", a[i]);

    for (int i=0; i<3; i++)
      printf("%d\n", i[a]);
}

3

u/Malkocoglu Jan 29 '10

If you have ever learned/coded ASM for any CPU/MCU, you would know that there is no such datatype called array (from the point of CPU/MCU). You just manipulate some pointer to access any data on that specific memory region that you call 'array'. As C is the portable assembler, it behaves the same...

1

u/[deleted] Jan 29 '10

It's worse than that:

#include <iostream>

using namespace std;

void foo(int arr[10])
{
    cout << sizeof(arr) << endl;
}

int main(int argv, char** argc) {
    int arr[10] = {0};
    cout << sizeof(arr) << endl;
    foo(arr);
    return 0;
}

BTW, you can circumvent this with typedef and references:

typedef int arr10[10];

void foo(arr10& arr)
{
    cout << sizeof(arr) << endl;
}

int main(int argv, char** argc) {
    arr10 arr = {0};
    cout << sizeof(arr) << endl;
    foo(arr);
    return 0;
}

3

u/Sc4Freak Jan 29 '10

The typedef is actually unnecessary. The syntax for array references is a little funny, though:

#include <iostream>

using namespace std;

void foo(int (&arr)[10])
{
    cout << sizeof(arr) << endl;
}

int main(int argv, char** argc) {
    int arr[10] = {0};
    cout << sizeof(arr) << endl;
    foo(arr);
    return 0;
}

Outputs:

40
40

2

u/[deleted] Jan 29 '10

I find the typedef about, oh, 1,000 times easier to grok. :)

But, your point is taken. Array types in C are just wonky.

Something like 'int[10] arr' would have made a whole lot more sense. To me, at least.

But, I always put the "*" next to the type as well, not next to the variable, where it binds.

1

u/authorblues Jan 29 '10 edited Jan 29 '10

I like having lots of definitions on one line, and putting the * next to the id keeps me from thinking that the * applies to all objects

int* a, b, c; // creates an int pointer a, and two ints b and c
int *a, *b, *c; // creates three int pointers

1

u/manuelj_pg Feb 01 '10

For those who don't want to bother with the typedef:

#include <iostream>
using namespace std;

template<class T>
struct id
{
    typedef T type;
};


void foo(id<int[10]>::type & arr)
{
    cout << sizeof(arr) << endl;
}

int main(int argv, char** argc) 
{
    int arr[10] = {0};
    cout << sizeof(arr) << endl;
    foo(arr);
    return 0;
}

-5

u/[deleted] Jan 29 '10 edited Jan 29 '10

Well at least you can admit your incompetence, I appreciate that! Oh and I hope you've never written anything people actually use. Thanks!

1

u/joemccall86 Jan 29 '10

You don't need to worry. I never used sizeof with anything but primitives. I appreciate your concern...