6.9a — Dynamically allocating arrays

In addition to dynamically allocating single values, we can also dynamically allocate arrays of variables. Unlike a fixed array, where the array size must be fixed at compile time, dynamically allocating an array allows us to choose an array length at runtime.

To allocate an array dynamically, we use the array form of new and delete (often called new[] and delete[]):

Because we are allocating an array, C++ knows that it should use the array version of new instead of the scalar version of new. Essentially, the new[] operator is called, even though the [] isn’t placed next to the new keyword.

Note that because this memory is allocated from a different place than the memory used for fixed arrays, the size of the array can be quite large. You can run the program above and allocate an array of length 1,000,000 (or probably even 100,000,000) without issue. Try it! Because of this, programs that need to allocate a lot of memory in C++ typically do so dynamically.

Dynamically deleting arrays

When deleting a dynamically allocated array, we have to use the array version of delete, which is delete[].

This tells the CPU that it needs to clean up multiple variables instead of a single variable. One of the most common mistakes that new programmers make when dealing with dynamic memory allocation is to use delete instead of delete[] when deleting a dynamically allocated array. Using the scalar version of delete on an array will result in undefined behavior, such as data corruption, memory leaks, crashes, or other problems.

One often asked question of array delete[] is, “How does array delete know how much memory to delete?” The answer is that array new[] keeps track of how much memory was allocated to a variable, so that array delete[] can delete the proper amount. Unfortunately, this size/length isn’t accessible to the programmer.

Dynamic arrays are almost identical to fixed arrays

In lesson 6.8 -- Pointers and arrays, you learned that a fixed array holds the memory address of the first array element. You also learned that a fixed array can decay into a pointer that points to the first element of the array. In this decayed form, the length of the fixed array is not available (and therefore neither is the size of the array via sizeof()), but otherwise there is little difference.

A dynamic array starts its life as a pointer that points to the first element of the array. Consequently, it has the same limitations in that it doesn’t know its length or size. A dynamic array functions identically to a decayed fixed array, with the exception that the programmer is responsible for deallocating the dynamic array via the delete[] keyword.

Initializing dynamically allocated arrays

If you want to initialize a dynamically allocated array to 0, the syntax is quite simple:

Prior to C++11, there was no easy way to initialize a dynamic array to a non-zero value (initializer lists only worked for fixed arrays). This means you had to loop through the array and assign element values explicitly.

Super annoying!

However, starting with C++11, it’s now possible to initialize dynamic arrays using initializer lists!

Note that this syntax has no operator= between the array length and the initializer list.

For consistency, in C++11, fixed arrays can also be initialized using uniform initialization:

Explicitly stating the size of the array is optional. Doing so can help catching errors early, because the compiler will warn you when the specified length is less than the actual length.

As of the time of writing, the GCC still has a bug where initializing a dynamically allocated array of chars using a C-style string literal causes a compiler error:

If you have a need to do this on GCC, dynamically allocate a std::string instead (or allocate your char array and then copy the string in).

Resizing arrays

Dynamically allocating an array allows you to set the array length at the time of allocation. However, C++ does not provide a built-in way to resize an array that has already been allocated. It is possible to work around this limitation by dynamically allocating a new array, copying the elements over, and deleting the old array. However, this is error prone, especially when the element type is a class (which have special rules governing how they are created).

Consequently, we recommend avoiding doing this yourself.

Fortunately, if you need this capability, C++ provides a resizable array as part of the standard library called std::vector. We’ll introduce std::vector shortly.

Question #1

Write a program that:
* Asks the user how many names they wish to enter.
* Dynamically allocates a std::string array.
* Asks the user to enter each name.
* Calls std::sort to sort the names (See 6.4 -- Sorting an array using selection sort and 6.8a -- Pointer arithmetic and array indexing)
* Prints the sorted list of names.

std::string supports comparing strings via the comparison operators < and >. You don’t need to implement string comparison by hand.

Your output should match this:

How many names would you like to enter? 5
Enter name #1: Jason
Enter name #2: Mark
Enter name #3: Alex
Enter name #4: Chris
Enter name #5: John

Here is your sorted list:
Name #1: Alex
Name #2: Chris
Name #3: Jason
Name #4: John
Name #5: Mark

Quiz solutions

1) Show Solution

6.10 -- Pointers and const
6.9 -- Dynamic memory allocation with new and delete

581 comments to 6.9a — Dynamically allocating arrays

  • salah

    Hi,this is working on my computer

    I am using Codelite Not visual studio

  • Oscar

    Hi, Thanks for this incredible resource! I have some suggestions for the quiz solution:

    1. Although we do not handle names with spaces, isn’t it still be better to use std::getline in getNameCount()? (And remove the new line from the stream after std::cin in line 9)?

    2. Line 15, 25, 38 should follow the best practice: when declaring a pointer variable, put the asterisk next to the variable name (except for the return type in functions).

    3. The naming of function getNames() is like a getter. So ideally, we expect it to *return* the names, not void. Perhaps its better to change the function name or its return type?

    4. The “names + length” in line 43 confused me initially because I thought we should pass in the pointer to the last element of the array, which is wrong. In Chapter 6.4, you used std::sort(std::begin(array), std::end(array)) but didn’t explain what begin() and end() are. I believe many beginners (like me) might assume that end() returns the last element of the array, while in reality it returns *the element after the last element* of the array. 

This is why I got confused when I saw “names + length” but not “names + length - 1” in line 43 until I checked the official docs for std::end(). I believe adding some extra explanations can help!

    I hope I'm not being too picky here, and I have no intention of criticizing! The original solution itself has already taught me a lot. I just wanna suggest some points that might be able to improve it further :D. Thanks again!

    • nascardriver

      1. No. We want an `int`, so we should extract an `int`. Extracting a string and then converting it is unnecessary. If you wanted to remove everything after the extracted number (eg. if the user entered "123 abc"), you should use `std::cin.ignore`.

      2. I disagree with this practice and don't know if Alex still agrees. I'll leave this to him.

      3. Changing the return type means we'd have to allocate the array in `getNames`. This would make ownership of the array confusing, which is dangerous, because it can quickly lead to memory leaks or double deletes. The function name could be changed to "readNames" or similar to make it look less like a getter, but I don't think this is necessary. The function still gets something, it just doesn't return it in the usual way. When you get to standard containers later in this chapter, the return type can be changed to `std::vector` to solve this issue.

      4. Thanks for pointing this out! I thought having the example in lesson 6.8a until iterators are introduced is enough, but apparently I was wrong in thinking that. I added a brief explanation of `std::begin` and `std::end` to lesson 6.8a.

      • Oscar

        Hi nascardriver thanks for the detailed reply!

        1. Sorry I made a typo. I meant to say getNames(), not getNameCount(). In getNames(), we require the user to enter all the names, so I thought it'd be better to use std::getline to allow for names with spaces. In that case, yes, we should use `std::cin.ignore` after line 9.

        2. Understood. FYI, I copied this best practice from Chapter 6.7 Introduction to pointers.

        3. Thanks for the detailed explanation! I'll keep on reading.

        4. Thanks for the amendment! I read it 6.8a again, and it's really helpful.

  • Oscar

    Hi, I found something interesting&confusing after modifying the example given at the top.
    Specifically, these two lines of code give different results:


    By monitoring my OS's memory usage during execution, I saw the top one requesting memory, while the bottom one doesn't seem to do so (at least I cannot see it in my monitor).

    However, the top one also takes more time to execute (probably because it needs to initialize all elements to 0), while the bottom one finishes instantly. I wonder if this is the reason that causes the monitor unable to display the memory usage when I executed the bottom line of code (because it finishes too fast). Or does the bottom one simply do NOT request any memory (because there's no initializer)? Many thanks in advance!

    • nascardriver

      > doesn't seem to do so [request memory]
      > finishes instantly
      This sounds like your program doesn't do anything. Compilers are allowed to optimize your code as long as the behavior doesn't change (In certain situations, they're allowed to change the behavior). A program that allocates memory and does nothing else can be considered equivalent to an empty program. Your compiler probably removed the allocation altogether, because it doesn't make a difference. Why this didn't happen in the first case, I don't know.
      If you want to check if this is what really happened, open the two binaries in a disassembler. The second one's main function should be empty (Apart from a return).

      • Oscar

        Thanks for the detailed explanation! It's interesting to know that compilers can optimize my code in such a way & the option of checking with a disassembler!

  • kavin

    Hi, for the quiz i did like this. I am able to input names, but after i enter 5th name i get error box saying "Debug assertion failed. Expression: string iterators in range are from different containers" Why is that ?

    I saw your solution. Why are u using a separate function to get input and why do u convert it using static_cast? Also why are you giving it an 'auto' type instead of "std::string" ?

    • nascardriver

      `*array` returns a `std::string`, so does your indirection in the second argument. You _can_ sort a single `std::string`, but that's not what you want to do. It sorts the characters in a single name. Because you're passing different strings to `std::sort`, you get an error.

      You can't use `std::begin` and `std::end` for dynamically allocated arrays. You need to calculate the begin and end manually, which you already did, partially.

      The end isn't the last element, it's the element after the last element.

      We pass pointers into the array to `std::sort`, not the elements themselves.

      > Why are u using a separate function to get input

      > why do u convert it using static_cast
      `new[]` wants a type convertible to `std::size_t`. Converting an `int` to `std::size_t` causes a warning. The cast silences the warning.

      > why are you giving it an 'auto' type instead of "std::string" ?
      We already say that it's a string array in the allocation. Repeating the type increases work when we want to update the code. If the type is as obvious as here, `auto` is a good choice.

      • kavin

        Thank you, i have few more doubts (Sorry for the lengthy questions)

        In the 1st example of this chapter,

        So for an dynamically allocated string array,'length' means 'number of arrays' and not 'number of characters' ? Because below here,

        [14] (which would substitute 'length') means number of characters in single array right?
        Also, the point of using dynamic arrays is not using size at compile time, but to choose an array length at runtime ? But declaring '14' defeats that purpose right? If i remove that 14 and write like this,

        i get this error, "error C3078: array size must be specified in new expressions"  Why ?

        >Because you're passing different strings to `std::sort`, you get an error<
        I thought std::begin and std::end would accept 1st character of first and last strings respectively and hence would sort all strings including the ones inbetween them in ascending order by comparing 1st characters in each string!

        >The end isn't the last element, it's the element after the last element.<
        In chapter 6.4 no additional info about std::sort is given. It's mentioned that, "We’ll talk more about std::sort in a future chapter." Where can i find these infos ?

        >`new[]` wants a type convertible to `std::size_t<
        Where do i find info about this or any other similar problems in future chapters ? (sorry, if i missed any information about this in previous chapters)

        • nascardriver

          The length of an array is the number of elements. If you have an array of `int`, it's the number of `int`s, if you have an array of `char`, it's the number of `char`s.

          > i get this error
          IIRC that code is legal but not properly compiled by all compilers. This example doesn't make a lot of sense, because the array length is known at compile-time.

          > I thought std::begin and std::end would accept 1st character [...]
          Nope, it takes iterators (pointers) to the array elements. `std::string` can be compared with `<` and `>`.

          > In chapter 6.4 no additional info about std::sort is given
          begin and end aren't explain until the lesson about iterators, but there's an example of manually calculating them in lesson P.6.8a (Last example).

          > Where do i find info about this or any other similar problems
          I don't think this is covered on learncpp yet. The array lessons are being updated, this conversion should be addressed.
          If enabled compiler warnings, you should've gotten a warning about the conversion from signed to unsigned. On cppreference you can see that `new[]` wants a `std::size_t`. A lesson about using cppreference is in the making.

  • Suyash

    Here's my solution...

    • nascardriver

      Fine code!

      In line 34 you're repeating the type (`std::string`). That's a good reason to use `auto`. It makes the code shorter, easier to update, and doesn't remove any information.

  • Alixsep

    Hi nascardriver.

    I have several Questions:
    1. For the alphabet sorting: Why doesn't my code work? when I run it, it is really messed up. (I don't want the correct code as reply, please explain this code's errors as long as possible).

    2. how to sort the entered name manually? (like bubble sort) (I mean to write a function to sort arrays instead of using the algorithm header)
    3. How can I dynamically allocate a multi dimensional array?
    4. One of my college classes is voluntary and requires to know python. Is it a good Idea to learn python the same time I am learning C++ via your website? If yes then can you name some good website (like yours) to learn python?
    5. And also, Can you name a good website like yours to learn and QT C++? (I wanna use QT to make apps right now, for example I want to make a meme generator app).

    Thanks nascardriver and happy 2020, I wish you bests.

    • nascardriver

      Hi Alixsep!

      When something doesn't work, please post the expected output, the actual output, and what you tried to do to fix it.
      - You allow any number of names to be chosen, but you only read/print the first 3.
      - You're mixing std::cin and std::getline. See lesson S.4.4b section "Mixing std::cin and std::getline()".
      - Initialize variables with brace initialization (`i`).
      - Use ++prefix instead of postfix++.

      This is no different from sorting numbers. `std::string` can be compared with `<` and `>`.

      This is covered in lesson 6.14. If you read two more chapters from there on, you'll find `std::vector`, which is safer and easier to use than manually allocating arrays.

      Using python is relatively easy, especially since you already know the basics of another language (C++). I guess you class doesn't require good knowledge of python, you should be able to learn it. I can't name a website.

      Not a tutorial, but the documentation and examples on the official Qt reference are pretty good. Thanks to Qt Quick, I don't think you'll need any C++ at all for a meme generator. You'll have to learn JavaScript though. Learning 3 languages plus QML at the same time might be too much, this is your choice.

      • Alixsep

        Thanks for the reply.

        1. OK thanks!
        2. Here I wrote it, Is it good?

        3. OK I will read it soon!
        4. No problem but I wish you could name a website.
        5. I am suffering from handling too much tasks in the daytime. I have to, I have one goal in my life and that is to become happy, and migrating from Iran an Islamic country *with sick and retarded people* is a must do, otherwise I can never reach happiness. so I am spending all my glorious teenage years of life to learn my be-loving task, programming, and destroying my joys (like being in relationship, taking trips, etc.)
        nascardriver I give you everything I have, please help me become successful, show me the way to migrate via programming. sorry for the comment, but my life is really messed up now.

        Thanks for your being. alex and nascardriver.

        • nascardriver

          2. Yep. Keep in mind: Unless you have a reason to implement something manually, use the std library versions. They're well tested, optimized, and their use is easier to read.
          You separated your code into sections by using comments. Using functions for separation is better, as it increases reusability.

          4. I didn't mean "I don't want to name a website", but "I'm unable to". Maybe someone else will see your comment and give you a hint. Until then, google will find you something.

          > I have one goal in my life and that is to become happy
          > so I am [...] destroying my joys
          That doesn't sound right. I'm not good with people, I can't give you life tips, but I can help you to learn programming.

  • chai

      auto* names{ new std::string[static_cast<std::size_t>(length)]{} };

    hi, in the answer why is length cast to size_t?

    • nascardriver

      Array declarations want a type that is convertible to `std::size_t` since C++14. Without the cast, compilers might cause warnings or errors.

  • Charan

    Hey, when I ran the above program,the program returned fine. My doubt is Iam deleting the pointer which is not dynamically allocated (or am I mistaken here?).I dynamically allocated memory in a function and returned the address,hence the pointer to which I allocated the memory ran out of scope.

    • nascardriver

      `get_strings::Y` ran out of scope, but the resource it was pointing to still exists. The pointer continues to be valid.

      • Suyash

        Is there a way to delete the pointer pointing to an array, before it goes out of scope in the above scenario while also returning the array? Would love to know the answer...

        Thanks in advance.

        • nascardriver

          No. If `get_strings` deletes the array, it will do so before the caller can use it. Manually allocating memory isn't good practice (The lessons are being updated), use a standard container, eg. `std::vector` (Introduced at the end of chapter 6) instead.

  • Tushar

    int *array{ new int[]{ 9, 7, 5, 3, 1 } };

    This is not working. It gives Error like " expected primary-expression before ‘]’ token ".

    • nascardriver

      It was missing the array length

      Thanks for pointing out the error!

  • nascardriver

    What's the error? What is happening? What do you want to happen? What did you do to try to fix it?

  • cnoob

    Hi! Ive tried to implement the manual sorting method. Is this the right way to do that?

    • nascardriver


      - Use functions. Your code is hard to read and not reusable.
      - Line 46: `std::string` and `std::string_view` support comparisons out of the box. `str < strComp`. - Line 34+: You can extract right into `*count`: `std::getline(std::cin, *count)`. - Line 30+: You're iterating over elements, but you need an index. Use a for-loop over indexes. - Returning 0 from `main` means that the program ran successfully. Return any non-zero value to indicate an error.

      • cnoob

        Yep, iterating over elements, but using pointers and introducing an extra int variable as counter was a pretty dumb move indeed.:D I didn't know that string_view and std::string support comparisons, thats cool! (in the end I didn't even need the string_view then. Here is the fixed code:

        • nascardriver

          Looks a lot better already :-)

          A couple more things to keep in mind:
          - Use single quotation marks for characters ('\n' instead of "\n").
          - You don't need `name` (Line 28).
          - `nameListLength` should be declared inside of the loop, because you don't need it outside.

  • Ryan

    I tried putting the solution all inside main() but the program crashes on the final for loop and prints "stack around variable was corrupted c++ array"

    • Ryan

      I updated it but i still get a segmentation error on the last for loop. Anyone know what is wrong?


      • nascardriver

        `sortAlphabetically`, first iteration of the outer loop, last iteration of the inner loop:

        Line 50, 52: You're accessing `names[nameCount]`, which doesn't exist.

        In your first solution, you're missing a `delete[]` and `array` is an array of pointers to `std::string`. It should be

  • Zwaffel

    Hey, i have come back to this chapter as i have a problem dynamically allocating an array of an object i made.
    So i have a MainMenu class and my main menu constains MenuItems class items'

    I'm trying to use the method that does not work as i want all my objects to keep a pointer to MainMenu.
    So i thought using MenuItem* menuItems = new MenuItem[5]{ &mainMenu }; wouldnt initilize them all with the adress of mainmenu but im getting

    E0289 no instance of constructor "MenuItem::MenuItem" matches the argument list

    • Zwaffel

      I tried adding an empty constructor but than only the first object gets initialized with the adress of mainMenu the rest is using the empty constructor.
      Should i be using a loop to initialized my self made objects ?
      Also not using gcc (i think) using the compiler that came with visual studio

    • nascardriver

      There's no way to initialize all elements of a built-in array to the same value without repeating the value for the number of elements (As you did in line 3).
      Judging by your code, you're at least in chapter 8. Don't use built-in arrays.

  • 3x3cuber

    How can we dynamically allocate a multidimensional array whose length we can enter at run-time?

  • Ethan

    To my knowledge, the only time we have seen std::sort up to this point in the tutorial is in lesson 6.4:

    How would you use std::begin and std::end in the solution for this lesson? Even though they work for the above snippet of code, I cannot get std::begin and std::end to work for this lesson's solution:

    • nascardriver


      `std::begin` and `std::end` don't work with dynamic arrays. Have a look at the last section of lesson 6.8a where we calculate begin and end manually.

  • Ged

    What is the difference, why use the size_t?

    • nascardriver

      `new` wants a `std::size_t`. Passing `length` (an `int`) causes a signed conversion (signed to unsigned). Depending on the compiler configuration, this might cause a warning or an error.

  • Ged

    1. Why not swap the values after the if statement?
    2. How do string arrays work, as I understand when we are sorting it checks the first letter, but what if we need it to sort by the 2nd letter as well? Does the program become more difficult?

    • nascardriver

      1. Then it's bubble sort, which is slower than selection sort. This lesson shouldn't be using a manual algorithm anyway, I updated it some time ago but seem to have forgotten to save it.
      2. `std::string` can be compared with `<` and `>`. It compares all letters until 2 letters don't match.

  • Tompouce

    So I was wondering, during all this tutorial you recomended using uniform initialization as much as possible when we need to create variables. But I couldn't help but notice that here, in your examples for allocating arrays dynamicaly, you use operator=, which I'm guessing is copy initialisation?

    If so, is this a case where copy initialisation is accepted, because it's easier to read or because there's no risks of unwanted narrowing conversions or something?
    I'm just curious because I've experimented and saw that something like this

    or even this

    seems to work as well.

    • nascardriver

      Some lessons haven't been updated to use brace initialization. Thanks for pointing this one out, I updated it :)
      Also note that you don't need to specify the size anymore if you initialize the array. I've removed that sentence from the lesson as well.

  • Federico

    Hi guys, I was wondering, in the quiz are we asked to modify the selection sort algorithm to sort the array of names as an exercise? I mean, could have we used

    or in this case, since we are using a dynamically allocated array, is it not raccomended ?

    • nascardriver

      `std::sort` should be preferred over custom implementations unless you have a very specific reason to sort by yourself.
      I assume the quizzes use custom implementations so you get practice in algorithms.

  • Connor

    Hey, was just wondering if this is an okay solution, and if you've got any feedback that would be of help please fire away :)
    P.s. I used a bubble sort instead of the selection sort recommended in the question, not sure why, just felt like it.

    • nascardriver

      Hey, some suggestions

      - Pass fundamental types (`int`, `double`, etc.) by value. Passing them by reference is slower.
      - Initialize your variables with brace initialization.
      - `tempInput` should be declared inside of the loop. This doesn't add any extra cost but reduces `tempInput`'s scope.

      • Connor

        Didn't know that passing fundamental types by value is faster. Thanks for the advice :) I've made the amendments you suggested. One question: should I still pass them as "const", even though passing by value means that the variable passed is not changed? Thanks.

        • nascardriver

          There's some debate about this. For one, it helps to catch errors and allows for more optimization. On the other hand, it can prevent certain optimizations.
          I can't give a definitive answer.

  • Luiz Carlo

    This is my shot at it, I tried it to make as robust as possible so there would be no ways to break it, since I have still to learn exception handling, I think it's pretty good.

    • nascardriver

      I think it's pretty good too. You could move the name input into its own function to de-clutter `main`.
      Standard functions live in the `std` namespace. So does `exit`. You need to include too.
      Some functions might be available without including their header or withing specifying their namespace. But more often than not this is compiler-dependent and your code might not work for others.

  • Cypeace

    Hey guys!

    this one was quite a nut to crack, took me at least 3 days and I'm still nowhere near to your code!
    I see from your solution, that you simply search for smallest element in array and the you swap it with the first. Then you repeat from next element, right?
    So how do you measure a "string", does < > operators compare each letter in string to the opposing element of "string" to determine, which has bigger letter? (brilliant if so)
    Here's my solution, which takes it too.. literally :-D

    • nascardriver


      - Initialize your variables with brace initializers.

      Your code looks good otherwise. You must've missed the hint "std::string supports comparing strings via the comparison operators < and >". Those operators compare letter by letter, until they find a difference.

      • Cypeace

        Oh indeed! I just love to complicate everything :-D But it was good exercise.. took me couple of days to figure it out lol

        But I guess in the end of the program, what really matters is the result.

        Thank you for all your support, see you in the next code!

  • Pave

    Okay. So the quiz was kinda confusing becouse i tought that passing an std::string array[] to a function would make it decay and could only access the first element.

    How is it that we can pass the array and access the whole array in a function? And some arrays will decay and can only access the first element.

  • hellmet

    So, in reality, name[0] is actually a pointer to the start of the string that std::string abstracts away from us? And name is technically identical to a char **?

    • You didn't say what type `name` is, I'm assuming it's `std::string`.
      > name[0] is actually a pointer to the start of the string
      No. It's a reference (Covered later) to the first char. You can take its address to get a pointer.

      > And name is technically identical to a char **?
      No. `std::string` stores a `char*`, but they're not identical. It's not guaranteed that the `char*` is the first member of `std::string`, so double indirection of an `std::string` isn't guaranteed to give you the string.

      • hellmet

        Ohh okay, I was thinking in analogies, but yes, you make it clear now. Also, I ran this code just before you replied, further cements your statements.

      • hellmet

        Also, did you mean

        • No. `c_str` is a member function of `std::string`.

          • hellmet

            (Oh and the 'names' here is the array in the example given above. )
            Hmmm... Okay, I asked 'cause I observed this

            • I was under the assumption that `names` is an `std::string`. If `names` is an array of `std::string`, ie. `std::string names[5]`, then

              > name[0] is actually a pointer to the start of the string
              `names[0]` is a reference to the first `std::string` in the array.

              > And name is technically identical to a char **?
              That's still wrong. `names` can decay to `std::string*`, so it's somewhat similar, but type-wise way different.

  • m3loo

    if I had a static array and I wanted to copy the values from the static array to a dynamic array, how would I do that?

    • You could of course also use a regular for-loop.

      `std::copy` can be parallelized and it's obvious that the line only copies data, it should be preferred.

      • m3loo

        first of all thank you very much!
        so I did use the for loop and it worked. now I wanted to copy a 2 dimensional static array in a one dimensional dynamic array (because the dynamic array can change it size so I thought that should be possible), and it kinda works but I also get those random numbers (meaning memory numbers).

        • > because the dynamic array can change it size
          If you create an array of size N, that array will always have size N. You can only "resize" it by deleting the old array and creating a new one.
          Without seeing your code, I can't tell you what you did wrong.

          • m3loo

            ahh ok. I just played around with

            • You're accessing invalid indexes. `i` and `j` run up to 3, but the highest valid index is 1. There are several issues with your code. Here's a fixed version. Please ask any questions that may come up.

              Or with `std::copy_n`

              Ideally you wouldn't use C-style arrays and multidimensional arrays in the first place.

              • m3loo

                thx again, I have some questions:

                1) so here, why did we have to use static_cast here? (I saw it get used, when for example we wanted to pass a double to an int.)
                2) then why did we use (array1) and in the next line we used (array1[0]), why the [0]?
                3) and my last question, why did we need the * here?

                • 1)
                  `std::size` returns an `std::size_t` which we need to convert to an `int`.

                  We want to know the length of the inner arrays. Since all inner arrays have the same length, we can use any of them. `array1[0]` is the most likely to exist, so that's what I used.

                  That's a multiplication.

  • Paul

    would you please help me?
    I'm getting desperate. I don't understand, why it's not working...THX

    #include <iostream>
    #include <string>
    void selectionSort(std::string *myArray, int numNames)

        // Step through each element of the array
        // (except the last one, which will already be sorted by the time we get there)
        for (int startIndex = 0; startIndex < numNames - 1; ++startIndex)
            // smallestIndex is the index of the smallest element we’ve encountered this iteration
            // Start by assuming the smallest element is the first element of this iteration
            int smallestIndex = startIndex;

            // Then look for a smaller element in the rest of the array
            for (int currentIndex = startIndex + 1; currentIndex < numNames; ++currentIndex)
                // If we've found an element that is smaller than our previously found smallest
                if (myArray[currentIndex] < myArray[smallestIndex])
                    // then keep track of it
                    smallestIndex = currentIndex;

            // smallestIndex is now the smallest element in the remaining array
                    // swap our start element with our smallest element (this sorts it into the correct place)
            std::swap(myArray[startIndex], myArray[smallestIndex]);

        // Now that the whole array is sorted, print our sorted array as proof it works
        for (int index = 0; index < numNames; ++index)
            std::cout << myArray[index] << ' ';

    std::string* enterName(int amount_names_)
        std::string *nameslist=new std::string[amount_names_];
        for(int count=0;count< amount_names_;++count)
            std::cout<<"Enter name #"<<count+1<<": ";

        return nameslist;

    int main()
        std::cout << "How many names would you like to enter? ";
        int amount_names{};
        std::cin>> amount_names;
        delete[] enterName(amount_names);
        return 0;

    • Please use code tags.

      - line 51 calls `enterName` again, creating a new array. The array from line 50 is leaked.
      - Initialize your variables with brace initializers.
      - Use your editor's auto-formatting feature.
      - If your program prints anything, the last thing it prints should be a line feed.

      "it's not working" doesn't help.
      What are you trying to do? Quiz X
      What's the expected behavior? Quiz X
      What is your input?
      What is the output?
      What is the expected output?
      What are the error messages?

  • Bankomat

    I was just wondering if it's ok to delete a dynamic array returned from a function by doing

    At least, as ok as it gets using dynamically allocated arrays in this  manner.

    • No, that's wrong.
      When you delete arrays, you need to use `delete[]`. You can only delete pointers to memory that was allocated with `new`. Your calculation seems like this is not the case. If your function did

      then the caller can

      Even though this works, it's messy. You should use a standard container instead (Covered in a few lessons).

      • Bankomat

        Ah, thank you.

        The reason I tried what I tried was because I was under the impression that only the first element in the array would be deleted by the caller as the array would decay to a pointer.

        I've already learned a few ways to get by this problem from future chapters but thanks nonetheless!

        • > I was under the impression that only the first element in the array would be deleted by the caller as the array would decay to a pointer
          It does decay, but `new[]` and `delete[]` use some internal information to keep track of the array's size. You can't access it, but `delete[]` can.

  • Allocate the outer array first, then allocate the inner ones in a loop.

  • Ramkumar

    Hi, great work dude ! .
    How can i allocate multidimensional arrays like this? during run time?

Leave a Comment

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