6.15 — An introduction to std::array

In previous lessons, we’ve talked at length about fixed and dynamic arrays. Although both are built right into the C++ language, they both have downsides: Fixed arrays decay into pointers, losing the array length information when they do, and dynamic arrays have messy deallocation issues and are challenging to resize without error.

To address these issues, the C++ standard library includes functionality that makes array management easier, std::array and std::vector. We’ll examine std::array in this lesson, and std::vector in the next.

An introduction to std::array

Introduced in C++11, std::array provides fixed array functionality that won’t decay when passed into a function. std::array is defined in the <array> header, inside the std namespace.

Declaring a std::array variable is easy:

Just like the native implementation of fixed arrays, the length of a std::array must be known at compile time.

std::array can be initialized using initializer lists or uniform initialization:

Unlike built-in fixed arrays, with std::array you can not omit the array length when providing an initializer:

However, since C++17, it is allowed to omit the type and size. They can only be omitted together, but not one or the other, and only if the array is explicitly initialized.

We favor this syntax rather than typing out the type and size at the declaration. If your compiler is not C++17 capable, you need to use the explicit syntax instead.

You can also assign values to the array using an initializer list

Accessing std::array values using the subscript operator works just like you would expect:

Just like built-in fixed arrays, the subscript operator does not do any bounds-checking. If an invalid index is provided, bad things will probably happen.

std::array supports a second form of array element access (the at() function) that does bounds checking:

In the above example, the call to checks to ensure the index 1 is valid, and because it is, it returns a reference to array element 1. We then assign the value of 6 to this. However, the call to fails because array element 9 is out of bounds for the array. Instead of returning a reference, the at() function throws an error that terminates the program (note: It’s actually throwing an exception of type std::out_of_range -- we cover exceptions in chapter 14). Because it does bounds checking, at() is slower (but safer) than operator[].

std::array will clean up after itself when it goes out of scope, so there’s no need to do any kind of manual cleanup.

Size and sorting

The size() function can be used to retrieve the length of the std::array:

This prints:

length: 5

Because std::array doesn’t decay to a pointer when passed to a function, the size() function will work even if you call it from within a function:

This also prints:

length: 5

Note that the standard library uses the term “size” to mean the array length — do not get this confused with the results of sizeof() on a native fixed array, which returns the actual size of the array in memory (the size of an element multiplied by the array length). Yes, this nomenclature is inconsistent.

Also note that we passed std::array by (const) reference. This is to prevent the compiler from making a copy of the std::array when the std::array was passed to the function (for performance reasons).


Always pass std::array by reference or const reference

Because the length is always known, range-based for-loops work with std::array:

You can sort std::array using std::sort, which lives in the <algorithm> header:

This prints:

1 3 5 7 9

The sorting function uses iterators, which is a concept we haven’t covered yet, so for now you can treat the parameters to std::sort() as a bit of magic. We’ll explain them later.

Manually indexing std::array via size_type

Pop quiz: What’s wrong with the following code?

The answer is that there’s a likely signed/unsigned mismatch in this code! Due to a curious decision, the size() function and array index parameter to operator[] use a type called size_type, which is defined by the C++ standard as an unsigned integral type. Our loop counter/index (variable i) is a signed int. Therefore both the comparison i < myArray.size() and the array index myArray[i] have type mismatches.

Interestingly enough, size_type isn't a global type (like int or std::size_t). Rather, it's defined inside the definition of std::array (C++ allows nested types). This means when we want to use size_type, we have to prefix it with the full array type (think of std::array acting as a namespace in this regard). In our above example, the fully-prefixed type of "size_type" is std::array<int, 5>::size_type!

Therefore, the correct way to write the above code is as follows:

That's not very readable. Fortunately, std::array::size_type is just an alias for std::size_t, so we can use that instead.

A better solution is to avoid manual indexing of std::array in the first place. Instead, use range-based for-loops (or iterators) if possible.

Keep in mind that unsigned integers wrap around when you reach their limits. A common mistake is to decrement an index that is 0 already, causing a wrap-around to the maximum value. You saw this in the lesson about for-loops, but let's repeat.

This is an infinite loop, producing undefined behavior once i wraps around. There are two issues here. If `myArray` is empty, ie. size() returns 0 (which is possible with std::array), myArray.size() - 1 wraps around. The other issue occurs no matter how many elements there are. i >= 0 is always true, because unsigned integers cannot be less than 0.

A working reverse for-loop for unsigned integers takes an odd shape:

Suddenly we decrement the index in the condition, and we use the postfix -- operator. The condition runs before every iteration, including the first. In the first iteration, i is myArray.size() - 1, because i was decremented in the condition. When i is 0 and about to wrap around, the condition is no longer true and the loop stops. i actually wraps around when we do i-- for the last time, but it's not used afterwards.

Array of struct

Of course std::array isn't limited to numbers as elements. Every type that can be used in a regular array can be used in a std::array.


House number 13 has 120 rooms
House number 14 has 30 rooms
House number 15 has 120 rooms

However, things get a little weird when we try to initialize the array.

Although we can initialize std::array like this if its elements are simple types, like int or std::string, it doesn't work with types that need multiple values to be created. Let's have a look at why this is the case.

std::array is an aggregate type, just like House. There is no special function for the creation of a std::array. Rather, its internal array gets initialized like any other member variable of a struct. To make this easier to understand, we'll implement a simple array type ourselves.

As of now, we can't do this without having to access the value member. You'll learn how to get around that later. This doesn't affect the issue we're observing.

As expected, this works. So does std::array if we use it with int elements. When we instantiate a struct, we can initialize all of its members. If we try to create an Array of Houses, we get an error.

When we use braces inside of the initialization, the compiler will try to initialize one member of the struct for each pair of braces. Rather than initializing the Array like this:

The compiler tries to initialize the Array like this:

The first pair of inner braces initializes value, because value is the first member of Array. Without the other two pairs of braces, there would be one house with number 13, 4 stories, and 30 rooms per story.

A reminder

Braces can be omitted during aggregate initialization:

To initialize all houses, we need to do so in the first pair of braces.

This works, but it's very confusing. So confusing that your compiler might even warn you about it. If we add braces around each element of the array, the initialization is a lot easy to read.

This is why you'll see an extra pair of braces in initializations of std::array.


std::array is a great replacement for built-in fixed arrays. It's efficient, in that it doesn’t use any more memory than built-in fixed arrays. The only real downside of a std::array over a built-in fixed array is a slightly more awkward syntax, that you have to explicitly specify the array length (the compiler won’t calculate it for you from the initializer, unless you also omit the type, which isn't always possible), and the signed/unsigned issues with size and indexing. But those are comparatively minor quibbles — we recommend using std::array over built-in fixed arrays for any non-trivial array use.

6.16 -- An introduction to std::vector
6.14 -- Pointers to pointers and dynamic multidimensional arrays

245 comments to 6.15 — An introduction to std::array

  • Q

    Thank you so much for this great chapter. I am learning a lot!

    >>std::array is a great replacement for built-in fixed arrays. It's efficient, <strong>in that it doesn’t use any more memory than built-in fixed arrays.</strong>

    Would you please elaborate on the bold part? How come is this possible? as we have to define the length of both types of arrays(fixed-size and std::array) at the compile-time!


    I have read these sentences like ten time, but i didn't get the idea.

    >>std::array is an aggregate type, just like House. There is no special function for the creation of a std::array. Rather, its internal array gets initialized as if it were a member of a struct.

    1: What do you mean by "special function for the creation of a std::array"? Is there special function for the creation of "primitive data types" which aggregate data types don't have?

    2: >> Rather, its internal array gets initialized as if it were a member of a struct.

    when you said "as if" it means it is a hypothetical situation and doesn't exist while std::array is a class and its members get initialized like members of a struct, right?

    • nascardriver

      The array's length is a part of the type, not a variable that is stored in the type. 2 `std::array`s with different lengths have different types. Every use of the array's length can be replaced by the compiler already. There's no need to store the length in memory and determine it at run-time.

      1: There are special functions (Constructors) for the creation of class-types (string, vector, array, etc.). `std::array` doesn't have a constructor.
      2: This is exactly what's happening. I updated the sentence to remove the "as if".

  • passionate_programmer

    Isn't it efficient to declare 'myArray.size()' outside the loop.

  • Typo

    >>In the above example, the call to checks to ensure array element 1 is valid, and because it is, it returns a reference to array element 1. We then assign the value of 6 to this. However, the call to fails because array element 9 is out of bounds for the array. Instead of returning a reference, the at() function throws an error that terminates the program (note: It’s actually throwing an exception of type std::out_of_range -- we cover exceptions in chapter 15). Because it does bounds checking, at() is slower (but safer) than operator[].

    There are two ",",which should have been " and"


    >>In the above example, the call to checks to ensure array element 1 is valid
    Wouldn't it better to say,"the call to checks to ensure index 1 is valid"?
    When you say, "array element 1 is valid", it kind of implies that element itself is valid not its index!

    > = 6; // array element 1 (IS) valid, sets array element 1 to value 6

    "is" is missing in the above.

    • nascardriver

      All updated. Thanks!

      • Typo

        Thank you too.

        There are three more (array element) left :

        In the above example, the call to checks to ensure the index 1 is valid, and because it is, it returns a reference to array element 1. We then assign the value of 6 to this. However, the call to fails because

        is out of bounds for the array.

  • Tim

    Hello Alex and Nascardriver,

    if I understand correctly, std::size() (which can be used for both build-in "C-style" arrays as well as "std::array" arrays) and .size() (which can only be used for std::array) both return a 'size_type' type (aka 'size_t' type), so if I want to make comparisons (e.g. in a for loop), I have to static cast the value that I want to compare it with to a 'size_t' type.

    On the other hand, the array index operator[] works with integral types for the build-in "C-style" array (so I can pass in any int type), but only works with 'size_type' type for the "std::array" arrays.

    I made some tests with the code below and got some interesting results.
    Could you explain me why the first 4 std::cout's work, but the last 2 don't?

    I thought they all wouldn't work, because operator[] expects a 'size_type' type for "std::array" arrays.

    • nascardriver

      The `size` functions can return whatever they want. Most often, it's `std::size_t`, but it doesn't have to be.
      Literals and enumerators are constant expressions. Constant expressions can be converted, because the compiler can determine if the conversion would cause a problem. `num` is not a constant expression, so you're not allowed to convert it to unsigned (Because `num` could be negative, the compiler doesn't know).

      • Tim

        Thank you for your answer. I understand why 'num' doesn't work now.

        Just to clarify for the literal and enumerator:

        So the literal and enumerator would be implicitly converted to 'size_type' in the code below?

        And for this code, the literal and enumerator are cast to type int and after that implicitly converted to 'size_type'?

  • Nguyen


    I copied and pasted the example program from this lesson into Visual Studio 2017.  It gives me some errors.

    E0441 argument list of class template"std::array" is missing
    E0065 expected a';'

    Am I missing anything?

    • nascardriver

      You didn't enable C++17 or VS 2017 doesn't support this feature. Make sure you enabled C++17 in your project. If that doesn't help, install a newer version of VS.

  • Alek

    hey,I got a few  questions.although you say we have to prefer std::array over array,I think in times when we can get our way with array it will be better than std::array.cuz you said passing an array to a  function is expensive so it will decay to a that regard std::array uses more memory,so my question is if I can get my way with array while passing it to function, is it still a better idea to use std::array ?

    2-in the case when the use of array is only in a function and thats all it's better to use std::array right ? cuz it's a struct and has member functions and etc... is this reasoning right ?

    3:we say and from what I searched on cppreference std::array is defined as a struct,so how is array defined ?

    4:I don't get about this sentence as well:This is why you'll see an extra pair of braces in initializations.
    of std::array. where do you mean ?
    thanks in advance!

    • nascardriver

      1. Pass the array by reference as recommended in the lesson, then there's no difference.

      2. I'm not sure I understand. `std::array` is safer and easier to use that built-in arrays due to its member functions.

      3. `std::array` is a template class, very similar to a struct, you'll learn about those later. Built-in arrays don't have a definition, they're built into the compiler.


      These are often forgotten.

      • Alek

        2:yes that's what I wanted to know.also you are using their member function : std::sort(myArray.begin(), myArray.end()); does the version of <iterator> work instead of these too ? like : std::begin(myArray) or for the end()..

        another question is I saw ppl use another pair of braces for fundemental types as well like:

        why do they so ? it also says it's required but we are ok with only one pair of braces for fundemental ones.. I saw this code in geeksforgeeks website.

        • nascardriver

          2. Yes, the `std::begin` and `std::end` call the member functions.

          The second pair of braces in `ar1` and `ar3` are _not_ required. It's perfectly clear what's happening without them. There's a compiler warning option that warns if the second pair of braces is missing, because of how `std::array` works (See section "Array of struct"). That's probably why these people are using them. Again, they're not required. Use them if you wish, we don't use them, because they don't add any value.

          • Alek

            thanks for your quick answer.Yes, the `std::begin` and `std::end` call the member functions. so both of the below  codes are valid :

            is there any difference though whichone to use?

            • nascardriver

              I use the `begin` and `end` member functions because I don't like how `myArray` has to be passed as an argument (Because that's how it's done in C, and I don't want to write C).
              However, that's not good enough of a reason to use the member functions. The free functions (`std::begin`, `std::end`) work with built-in arrays and can be added for other classes without modifying those classes, which makes them superior to the member functions.

              Note that since C++20 you need `begin` and `end` in a lot fewer places, you can just do

  • koe

    Hi, I got this error

    It was fixed by using

    • nascardriver

      Those braces are unnecessary. If the type you're initializing has only a single member (Which is the case for `std::array`), there's no reason to use another set of curly braces even if the member is not scalar. I suggest removing -Wmissing-braces from you compiler options.

  • Constantine

    I found that an initialization works this way:

    I don't know whether it's standard or not.

    • Gabe

      Yeah, if you add the struct House for each of them, it works as well:

      std::array<House, 3> houses{
                  House{ 13, 4, 30 },
                  House{ 14, 3, 10 },
                  House{ 15, 3, 40 }

  • Ambareesh

    I don't understand the rationale behind using myArray.size() here. We have already hard-coded (or used a magic number) 5 in std::array<int,5> in the for-loop initialization. What's the point in using myArray.size() - especially considering the problems of signed/unsigned ints ?

    • nascardriver

      Adding more magic only makes the code worse. The `std::array::size_type` could be replaced with `decltype(myArray)::size_type` (decltype "returns" the type of a variable) to get rid of the magic. However, it's much easier, and still correct, to use `std::size_t`. I've removed the alias example from the lesson to shorten the transition from the verbose `size_type` to `std::size_t`.

  • Jimmy Hunter

    Is the ampersand used here in this snippet a typo or is this a use of the auto keyword that I do not remember from an earlier lesson?

    "for (const auto& house : houses.value)"

    auto& is used twice on the page.

    • nascardriver

      It's a reference from lesson P.6.11 and P.6.11a. We don't want to create copies of the houses as we iterate over them, so we use references.

      • Jimmy Hunter

        Thanks for the explanation.  I went back and reviewed.  I did not connect the analogous rules for pointer symbol placement and reference symbol placement.  Lesson P.6.7 Introduction to pointers has a great explanation about the location of the asterisk pointer symbol.  However, I could not find a similar explanation for ampersand reference symbol placement/location.  I should have inferred it.  And later, when I typed the reference example in Visual Studio 2019, the VS editor automatically moved my ampersand to be a suffix to auto instead of a prefix to the variable name.

        It's a little confusing for this old guy, but I will master it with practice.  I

  • Jimmy Hunter

    One more typo to fix, if you don't mind.

    "There is no special function for the creation of a std::array, its internal array gets initialized as if it were a member of a struct."

    I think this is actually two sentences?  Needs a period instead of a comma.

    Or, it's an independent clause and a dependent clause, which should be joined by a semi-colon, if I remember my 10th grade English correctly.

  • Jimmy Hunter

    std::array can be initialized using an initializer lists or uniform initialization:

    Can be corrected either of two ways:
    std::array can be initialized using initializer lists or uniform initialization:


    std::array can be initialized using an initializer list or uniform initialization:

  • frequent_visitor

    So, in the case of std::array, can we not dynamically allocate it? Is there no way (let's say) such that the user give us n integers and we allocate an array of std::array type?

    • Wambui

      I had this same question after reading this chapter. After some research, apparently what you have in mind is called Variable Length Arrays (VLAs) and they are illegal in C++. They exist in C. However, there are some compilers that have some extensions that allow them to accept some non-standard C++ things like VLAs. Here is a link I found from stack overflow where this has been discussed a lot(

      I am however also waiting for comments on this from Nascardriver/Alex

      • frequent_visitor

        After reading some of the older comments, it turns out what we're talking about is just the next lesson, std::vector. It uses the functionality which I was talking about in my previous comment.

      • nascardriver

        Don't use compiler extensions. What you're looking for is `std::vector` (Or dynamically allocated arrays).

  • kitabski

    Isn't it better just to do like this:

  • Harshit Agrawal

    Why is &myArray used in printLength() function? I think we should use just myArray.
    Also, please elaborate the usage of const in this case?

    • nascardriver

      We're passing `myArray` by reference to prevent creating a copy of it. Because the function doesn't modify the array, we mark it `const`. We talk about about reference parameters later in this chapter.

  • salah

    hi, I tried that, but it did not work

    size(my_array)...but this worked my_array.size()

  • Jason

    In line 5 of the 5th snippet

    the <double, 2> seems to be in the wrong location? Shouldn't it be behind 'std::array' instead of 'myArray'?

  • Deepak Budha

    When I run any of the given programs on Code::Blocks,I get the two errors:
    1.error: missing template arguments before 'array'
    2.error: 'array' was not declared in this scope

    Why is it happening?

  • Luiz Carlos

    Can't I just cast myArray.size() to int instead of using an index of a different type?

    • nascardriver

      You can. Depending on the situation, that might be more work than changing the index type.

      • Luiz Carlos

        Thanks, I also just realized that it could be problematic for really large arrays, (which likely wouldn't be fixed anyways) since unsigned ints can have greater positive value than signed ones (half of it).

  • BP

    I'm currently to busy to really keep on learning Cpp right now and will continue when I have some time free, but out of intrest I decided to use Cpp to quickly do something. I need to learn all the amino acids for biochemistry and I thought it would be usefull to have some code that randomly chooses a type(one letter name, three letter name, full name, and image(through a number refering to a piece of paper with me)). and then in a random sequence prints of that type every animo acid. So if the oneLetterName was chosen, then 20 letter would have been print.

    I thought as well that I might as well post the code here to see if there's room voor improvent(which always exists).
    So if somebody has some free time please look this through, and yes it does involve std::array.

    And in another file:

    I recon this is spaghetti code...
    Thanks eitherway!

    the code I used to shuffle the array, I copied from the internet. It gives a couple of warnings but works.
    I don't really understand how it works, as I believe I seeded mersenne twice?

    • Hi!

      - `startingType` should be of an `enum class` type.
      - You should be using a struct to store the names

      - Use `constexpr` for compile-time constants.
      - Don't use `std::system`, it work work on other platforms.
      - Line 42-45: You're losing the ability to find the other properties of a given entry based on index. Eg. if you generate the three letter code "Gly", your program doesn't know the full name, one letter name, or image index for "Gly" anymore. By using a struct, everything stays together and you could print the solution.
      - Line 42-45: You're shuffling everything, even the arrays you don't use anymore.
      - Explicitly initialize variables which you read from before writing to them.

      > I believe I seeded mersenne twice
      You have two distinct mersenne twisters. You're seeding them from different sources, so they should be different. It'd be better to use a single twister tough.
      You're using `std::random_device`. It might not be supported on all systems and shouldn't be used without checking its entropy (ie. check if it works).

      > through a number refering to a piece of paper with me
      So simple, I like it :)

  • p1

    So what is the reason to use this over normal arrays?

  • Hai Linh

    Why doesn't operator[] have bounds checking? After all, one can overload operator[] to add bounds checking, so why wouldn't std::array's operator[]?

    Edit: We learn exceptions in chapter 14, not chapter 15 (chapter 15 is about smart pointers)

  • Samira Ferdi

    Hi, Alex and Nascardriver!

    How to delete array's element?

  • potterman28wxcv

    Hello! Do you have any thoughts on using `auto` instead of `std::array<int, 5>::size_type` in the for loop?

    • The issue is that you need a 0 of type `std::array<int, 5>::size_type`, but you won't get that from the array.

      You might be tempted use `myArray.size() - 1` to initialize `i` and try to iterate in reverse.
      But unsigned integers get you, this will cause an infinite loop.

      The only way to get the start of the array is through `myArray.begin()`, but that gives you an iterator. Since the whole point of a regular for-loop is that you have an index, this doesn't help.

      `std::array` is guaranteed to use `std::size_t` as its index type (@Alex), so you can use that. This isn't guaranteed for all standard containers, check cppreference if you're unsure what your container's types are

      std::vector with an implementation defined index

      std::array with a guaranteed index

  • Anastasia

    Do we have to write a separate function for every std::array's length we eventually may want to pass to that function? I mean isn't it a bigger downside than the fact that the regular array decays to a pointer if we can just pass it's length along with it and the same function will work for (build-in) arrays of all sizes?

    And a bit unrelated question, but in S.4.8 Alex wrote that `auto` keyword shouldn't work with function parameters. Yet, this snippet compiles just fine and without any warnings and works as expected. Has it been changed in C++17?

    • Hi!

      `std::array` always has to know its size. You could let the compiler generate functions for different sizes by using templates.
      If you want dynamically sized lists, `std::vector` is what you're looking for (Covered later in this chapter).

      `auto` cannot be used for function parameters. Make sure you followed lesson 0.10 and disabled compiler extensions.

      • Anastasia

        > `auto` cannot be used for function parameters. Make sure you followed lesson 0.10 and disabled compiler extensions.

        You're right, I've added `-pedantic-errors` flag and it doesn't compile now. I'd never have thought it's just an extension.

        I'll wait untill we learn about templates then. Thank you!

  • noobmaster

    Is that because arr1 decays to pointer when passed to .size() function?

  • Tamara

    I'm a bit confused by this part: "Due to a curious decision, the size() function and array index parameter to operator[] use a type called size_type, which is defined by the C++ standard as an unsigned integral type. Our loop counter/index (variable i) is a signed int."
    But if that's the case then haven't we've been having type mismatches in our code every time we would use for loops with built-in fixed arrays, for example like this:

    Now, by using typeid(size(myArray)).name(), I can see that the return type of size() is, indeed, an unsigned int and I do get a warning for it. But when I remove that, I get no type mismatch warning for the array index myArray[i]. Why is that? And also, how could I see the type of the array index parameter using typeid? If I just used typeid(myArray[i]).name() that would return the type of the array element, int in this case.

    Thanks in advance.

    • Line 4 should cause a warning, because you're comparing signed to unsigned. If it doesn't make sure you enabled sign comparison warnings in your compiler settings.
      Line 6 doesn't cause a warning, because array indexes only have to be integral types. This is not the case for `std::array`. `std::array` wants its `size_type` type as an index.

      • Tamara

        Oh, so it differs with std::array in that regard. But then one more thing. When I copied this entire piece of code from the lesson into VS:

        it gives me a warning for Line 9, for the "myArray.size()" as it should. But in the lesson it also says that the array index "myArray[i]" is a type mismatch and I'm not getting a warning back for that line. I'm assuming the sign comparison warnings are enabled since I'm getting a warning for Line 9.

        • Line 9 is a sign comparison,
          Line 10 is a sign conversion.
          Sorry, I don't know how to control warnings in VS, you'll have to look it up on your own.

          • Tamara

            Ah, I get it now. Thanks for the help!

          • Yaroslav

            can i ask why would we not just use

            or even better cast .size() to signed so 'i' will remain signed and we could use it down in comparison with signed by code

            ? thank you

            • > why would we not just use `unsigned int i`
              For one, we don't know that `arr.size()` returns an unsigned int. We could use `std::size_t`, but that's and unsigned integer type and looping over unsigned integers (Or anything involving unsigned integers, really) is prone to wrap arounds or unexpected signed -> unsigned promotions. It's easier to stay with signed integers as long as you don't need the high positive range of unsigned.
              A cast is the preferred solution. Since C++20, you can replace `arr.size()` with `std::ssize(arr)`, which returns the size as a signed integer, making the cast unnecessary.

              • Yaroslav

                thank you @nascardriver.

              • Ambareesh

                "For one, we don't know that `arr.size()` returns an unsigned int. "

                What do you mean exactly? What else could arr.size() return ? Also, either way, if the length fits inside signed int limits, there is no harm in casting it to signed int right? Is this bad practice?

                • nascardriver

                  `arr.size()` returns `std::size_t`, which is an unsigned integer.

                  it could be any of those.

                  If you know that the length fits into an `int`, there's no harm in casting it, if you need to. In the above example, there's no need for a cast. In fact, we'd have to cast the `int` back to a `std::size_t` when we want to use it to access the array. Using an `int` to access an `std::array` causes a compiler warning with a high enough warning level, because `std::array` expects an `std::size_t` for its `operator[]`.

  • darshan

    Why does

    give an error?

  • Why i am getting error in the above program?
    But in this one.

    • Snippet 1
      * Line 5: Initialize your variables with brace initializers.
      * Line 2: Limit your lines to 80 characters in length for better readability on small displays.

      Snippet 2
      * Line 5: Initialize your variables with brace initializers.

      If you're getting errors, post the error message.
      You're using @std::string without including <string>.

      • Oh! I actually never included string library unless i had to do string operations as it worked all the time and this is the first time i used std::string  in global scope. It worked when i included string library. But it also works when i initialise keywords array inside the main even without using string library.

        Why this happens ?
        Thanks a lot for the suggestions. :)

  • Shri

    Hi Alex, in this chapter you have mentioned that one of the reasons to use std::array is that, when passing std:array to a function (where the function parameter is a reference to the argument), it does not decay into a pointer.

    But in later chapters you show that even built-in arrays can be passed by reference (along with mentioning the length of array) such that the argument does not decay into a pointer.

    Based on this, do you think this advantage (std:array not decaying into a pointer when passed by reference into a function) should be removed from this chapter?

Leave a Comment

Put all code inside code tags: [code]your code here[/code]