Skip to content

Raw arrays

Raw arrays

An array is a sequence of objects of the same type that occupy a contiguous area of memory.

Traditional C-style arrays, or Raw Arrays, are the source of many bugs, but are still common, especially in older code bases.

In modern C++, we strongly recommend using std::vector or std::array instead of C-style arrays.

1
2
3
4
5
6
constexpr int n = 3;
int a[n];
a[0] = 1;
a[1] = 2;
a[2] = 3;
std::cout << "a: " << a << '\n';

1
2
3
std::cout << "a[0]: " << a[0] << '\n';
std::cout << "a[1]: " << a[1] << '\n';
std::cout << "a[2]: " << a[2] << '\n';

1
2
3
std::cout << "&a[0]: " << &a[0] << '\n';
std::cout << "&a[1]: " << &a[1] << '\n';
std::cout << "&a[2]: " << &a[2] << '\n';

1
int b[] = {1, 2, 3};

1
2
3
for (size_t i = 0; i < n; ++i) {
    std::cout << "b[" << i << "]: " << b[i] << '\n';
}

1
2
3
4
std::cout << "b: " << b << '\n';
std::cout << "&b: " << &b << '\n';
std::cout << "b[0]: " << b[0] << '\n';
std::cout << "&b[0]: " << &b[0] << '\n';

1
2
3
4
std::cout << "b[1]: " << b[1] << '\n';
std::cout << "&b[1]: " << &b[1] << '\n';
std::cout << "b[2]: " << b[2] << '\n';
std::cout << "&b[2]: " << &b[2] << '\n';

1
2
3
char c[] = { 'a', 'b', 't', '\0' };
// same as:
char d[] = "abt";

1
2
std::cout << "c: " << c << '\n';
std::cout << "d: " << d << '\n';

Share Snippets