Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Now that we have std::array what uses are left for C-style arrays?

std::array is vastly superior to the C arrays. And even if I want to interoperate with legacy code, I can just use std::array::data(). Is there any reason I would ever want an old-school array?

like image 897
R. Martinho Fernandes Avatar asked May 24 '11 13:05

R. Martinho Fernandes


People also ask

What is C-style array?

A C-Style array is just a "naked" array - that is, an array that's not wrapped in a class, like this: char[] array = {'a', 'b', 'c', '\0'}; Or a pointer if you use it as an array: Thing* t = new Thing[size]; t[someindex]. dosomething();

Why use std:: array?

std::array provides many benefits over built-in arrays, such as preventing automatic decay into a pointer, maintaining the array size, providing bounds checking, and allowing the use of C++ container operations.

Can C-style arrays be used with STL algorithms?

So - yes, a pointer can very well be used with STL algorithms.

Do C-style arrays have methods?

c-style array as method parameter with size information Of course, the template concept can also be used for a c-style array. Instead of passing a pointer to the first element, you can pass the array as a reference to template function. This will allow to pass the array with its specific size.


1 Answers

Unless I've missed something (I've not followed the most recent changes in the standard too closely), most of the uses of C style arrays still remain. std::array does allow static initialization, but it still won't count the initializers for you. And since the only real use of C style arrays before std::array was for statically initialized tables along the lines of:

MyStruct const table[] = {     { something1, otherthing1 },     //  ... }; 

using the usual begin and end template functions (adopted in C++11) to iterate over them. Without ever mentionning the size, which the compiler determines from the number of initializers.

EDIT: Another thing I forgot: string literals are still C style arrays; i.e. with type char[]. I don't think that anyone would exclude using string literals just because we have std::array.

like image 77
James Kanze Avatar answered Sep 25 '22 00:09

James Kanze