Search

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:

One caveat, in C++11 you can not initialize a dynamically allocated char array from a C-style string:

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

Also note that dynamic arrays must be declared with an explicit length:

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.

Quiz

1) Write a program that:
* Asks the user how many names they wish to enter.
* Asks the user to enter each name.
* Calls a function to sort the names (modify the selection sort code from lesson 6.4 -- Sorting an array using selection sort)
* Prints the sorted list of names.

Hint: Use a dynamic array of std::string to hold the names.
Hint: std::string supports comparing strings via the comparison operators < and >

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
Index
6.9 -- Dynamic memory allocation with new and delete

305 comments to 6.9a — Dynamically allocating arrays

  • John Halfyard

    So I don't want to peak at the solution. Initially tried a 'for' command, then switched to a 'do' command but got the same output.  It seems the code is keeping over arraynames[0].  The code below is just for testing entering 4 names.  Once I get that done, I'll move to the sort.  It prints out the last three of the names but doesn't accept entry on the first name?  Can you assist?

    • Alex

      You're running into an issue because you're mixing operator>> and std::getline. I describe this issue, along with a solution, in this lesson: http://www.learncpp.com/cpp-tutorial/4-4b-an-introduction-to-stdstring/

  • Leea

    Hi Alex,

    I am wondering why the syntax to declare a dynamic array looks as though we are declaring a pointer. That is why is there an asterisk between the data type and the variable name?  

    Are we technically declaring a pointer that "un-decays" into an array once the length is specified???

    • Alex

      Because you _are_ declaring a pointer. 🙂

      When we call array new, it allocates length * element size bytes of memory. The address of that memory block is returned by operator new. In order to use that memory, we typically stuff that address into a pointer so we can use it later. In the above example, that pointer is named array. We then access the array through the pointer, since operator[] is really just doing pointer arithmetic anyway.

      There's no such thing as un-decaying.

  • D Brown

    Hello Alex,

    I keep getting an error and am not sure where it originates from. The "<<" operator won't except type std::string.
    The error is

    (Error    C2679    binary '<<': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion))    

    The code is as below and the error is on the last line of code:

    #include <algorithm> // for std::swap, use <utility> instead if C++11
    #include <iostream>
    #include <string>
    #include "stdafx.h"

    int main()
    {
        using namespace std;
        // Find out how many names the user would like to enter
        int numofNames;
        cout << "How many names would you like to enter?\n";
        cin >> numofNames;

        // dynamically allocate an array of strings based on the number of names
        std::string *names = new std::string[numofNames]();

        // Iterate until the last name is entered and store these strings in there respective locations in the array
        for (int iteration = 1; iteration <= numofNames; ++iteration)
        {
            cout << "Enter name #" << iteration << ":\n";
            char Zname;
            cin >> Zname;
            names[iteration - 1] = Zname;
        }
        std::cout << names[1];
    }

  • Taksh

    Hey Alex,

    I don't understand how in the solution, the program told us which string was smaller. How is it possible to compare strings like this?

    Thanks in advance.

    • Alex

      std::string includes comparison operators < and > that return a boolean value indicating how the two strings compared alphabetically.

      So "Alex" < "John" would evaluate to true, since "Alex" appears before "John" alphabetically, assuming "Alex" and "John" are std::strings and not C-style string literals.

  • Eric

    Hi, i have written a quiz task of dynamicly allocating arrays , but cannot figure out why it doesnt work properly , can you please help me?And why do most people #include <string> if it works without including? Thanks anyway.

    #include <iostream>
    #include <utility>

    void getNames(std::string *array , int arrayLength)
    {
        for(int i = 1; i != (arrayLength + 1); ++i)
        {
            std::cout << "Enter name #" << i << ": ";
            std::cin >> array[i - 1];
        }
    }

    void sortArray(std::string *array, int length)
    {
        for (int startIndex = 0; startIndex < length; ++startIndex)
        {
            int smallestIndex = startIndex;

            for (int currentIndex = startIndex + 1; currentIndex < length; ++currentIndex)
            {
                if (array[currentIndex] < array[smallestIndex]);
                    smallestIndex = currentIndex;
            }

            std::swap(array[startIndex], array[smallestIndex]);
        }
    }

    void printNames(std::string *array , int arrayLength)
    {
        std::cout << "\nHere is your list:" << std::endl;
        for(int i = 0; i != arrayLength; ++i)
            std::cout << array[i] << std::endl;
    }

    int main()
    {
        int arrayLength;
        std::cout << "How many names would you like to enter? ";
        std::cin >> arrayLength;
        std::string *array = new std::string[arrayLength];
        
        getNames(array,arrayLength);
        sortArray(array,arrayLength);
        printNames(array,arrayLength);
        
        delete[] array;
        array = nullptr;
        return 0;
    }

    Console:
    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: John
    Name #2: Jason
    Name #3: Mark
    Name #4: Alex
    Name #5: Chris

    • Alex

      This seems like the perfect opportunity for you to learn how to use the debugger. You can watch each of the array elements, and see how iterating over the loops changes them.

      You should always include all of the headers you use yourself. Since you use std::string, you should include the string header. Because even though another header might do it for you, you shouldn't rely on that being true in the future.

  • Ashish Rana

    Here is mine, Is it bad form to swap inside the if statement?

    Btw, great tutorials! Very thorough. Thanks for all the effort you've put into this.

  • Cotrim

    Hey Alex got a random question.

    I have this code:

    it works fine this way but the first time around I tried to use

    in line 13 and it failed to get the string, crashed the program and became so bugged I couldn't stop it even in Task Manager had to reboot the pc... What is wrong with it? as far as I understand it was a legal use of it >< (must not be ofc but I don't get it)

    • Alex

      You're running into the issue where after getting the number of names, the '\n' character is still stuck in the input stream, so std::getline() is just extracting that rather than asking the user for input. You need to call std::cin.ignore(32767, '\n') to get rid of it before you call std::getline().

      The other program is that you've created enterName as a recursive function (a function that calls itself), but that hasn't been done properly. Switch to an iterative version (use a loop to do error handling) and I'm guessing your crashing issue will go away.

  • Aditya Pratap

    Hi Alex,I wrote the following code and got the desired result,please check if it contains any logical mistake.

    • Alex

      Looks fine to me. There's no need to set array to nullptr at the end of main() since array will go out of scope immediately after anyway.

  • AMG

    Alex,
    As we know, sizeof() does not work properly when an array is passed as an argument to function. How about delete[]? Thanks.

    • Alex

      delete[] works (otherwise, we'd never be able to delete a dynamically allocated array since we'll always only have a pointer pointing to that memory).

  • Lynsey Lehmann

    Hello, although I am close to understanding pointers and how they are referred to in code, the first example on this page with new[] and delete[] confused me a bit. Why is it that when you dynamically allocate array (int *array = new int[length]) you refer to the array with * and then in the next line it is no longer *array, only (array[0] = 5;). In the previous section you had a similar example but in that case after dynamical allocating *ptr (int *ptr = new int;) you followed the code with (*ptr = 7) not ptr=7. I am confused on when I should know to put the * and when I should leave it off. Thank you so much in advance.

    • Alex

      When you declare a pointer, you use the asterisk (*) to indicate that the variable is a pointer instead of a normal variable.

      When we use a pointer, there are 3 things we can do with it:
      1) Explicitly dereference the pointer (using an asterisk) to access the value the pointer is pointing at (*ptr = 7)
      2) If the pointer is pointing at a struct or class, we can use the -> operator to access the member (ptr->someMember = 7)
      3) If the pointer is pointing at an array, we can use the [] operator to access an element (array[0] = 5)

      #2 and #3 have an implicit dereference done inside the operator.

      So basically, you use the asterisk when declaring pointers, and when you're explicitly dereferencing them.

  • justAnotherConfusedStudent

    Stylistic question:

    What's the difference between

    and

    When would we prefer one over the other?

  • Jon uk

    Hi Alex,

    I have to say, I am starting to struggle a bit here, because PHP handles arrays differently, I am having problems with the difference between de-referencing a pointer, pointer declarations and why is array defined with *array, it's kind of like walking through mud at this stage, however this is the solution I came up with for the quiz ... eventually.

    I left some commented out debug code to describe my thought processes whilst I was trying to figure this out

    • Alex

      > I am having problems with the difference between de-referencing a pointer, pointer declarations and why is array defined with *array

      De-referencing a pointer is done when we want to get the value of the variable the pointer is pointing at.
      Array is defined with *array because build-in arrays decay into a pointer when we pass them to a function. So if the caller passes us array, we should expect to receive a pointer to the array. An alternate syntax would be std::string array[], which may be more intuitive.

  • MYLESMAN

    In the quiz question, is there a way to include white spaces in the elements?

    Regards, MYLESMAN

  • I am still confused how this works:

    Could you please explain that?
    Thank you.

  • pfroehlich2004

    Tweaking the code just a little and using a fixed array (see below) seems to produce the desired result. As this is entirely new to me, can you explain why we should use a dynamically-allocated array in this case? (And btw, thanks immensely for the site. I'm taking my first-ever programming course at uni right now and was having a hard time keeping up until someone recommended learncpp.com)

    #include <iostream>
    #include <string>
    #include <utility> // for std::swap, if you're not C++11 compatible, #include <algorithm> instead

    void sortArray(std::string *array, int length)
    {
        // Step through each element of the array
        for (int startIndex = 0; startIndex < length; ++startIndex)
        {
            // smallestIndex is the index of the smallest element we've encountered so far.
            int smallestIndex = startIndex;

            // Look for smallest element remaining in the array (starting at startIndex+1)
            for (int currentIndex = startIndex + 1; currentIndex < length; ++currentIndex)
            {
                // If the current element is smaller than our previously found smallest
                if (array[currentIndex] < array[smallestIndex])
                    // This is the new smallest number for this iteration
                    smallestIndex = currentIndex;
            }

            // Swap our start element with our smallest element
            std::swap(array[startIndex], array[smallestIndex]);
        }
    }

    int main()
    {
        std::cout << "How many names would you like to enter? ";
        int length;
        std::cin >> length;

        // Allocate an array to hold the names
        std::string names[length];

        // Ask user to enter all the names
        for (int i = 0; i < length; ++i)
        {
            std::cout << "Enter name #" << i + 1 << ": ";
            std::cin >> names[i];
        }

        // Sort the array
        sortArray(names, length);

        std::cout << "\nHere is your sorted list:\n";
        // Print the sorted array
        for (int i = 0; i < length; ++i)
            std::cout << "Name #" << i + 1 << ": " << names[i] << '\n';

        

        return 0;
    }

    • Alex

      This is not legal C++:

      By assigning a non-const length to a fixed array, you're defining what's called a "variable length array" (VLA). C++ does not currently support VLA's. However, some compilers will let you create them anyway, for backwards compatibility with C99 (which does support them).

      In C++, if your array length is not constant, you must use dynamic allocation if you want to remain standards compliant.

  • Zangin

    Thanks Alex!
    Another difference between fix and dynamic array is in the declaration, when the length should be provided for the dynamic array. For example:
    int fixArray[]{ 1, 2, 3 }; // Working. It doesn't need length.
    int *dynamicArray = new int[] {1, 2, 3}; // Not working. Length is missing.
    The above case works if the length is provided:
    int *myArray{ new int[2] {1,2,3} }; // Working.

  • Domi

    Uhm hi, I just used std::sort(array, array + length);

    It's literally 1 line vs this huge function and it worked perfectly? Are there any downsides to doing it this way?

  • Tim Hothersall

    I am reliant on an C api for postgresql which wants a char ** array for PQexecparams and am using vector<string> and only converting when absolutely necessary.  Is there anything wrong with doing it like this or is there another easier or better way (I can't use libpqxx because it won't build on AIX so am stuck with libpq-fe.h):

    PS. This is in a class  and has some error catching in the production code.

    • Alex

      Seems fine as long as you're not having performance issues from having to do a lot of conversions.

      • Tim Hothersall

        No doubt there will be, but it is not noticeable and I can't really think of an alternative other than using char** which is going to give me a lot of C code scattered all over my program rather than just in a couple of classes.  Because everything decays to a char * with postgresql I have to do a lot of converting, but the whole program is just an interface to a database and so is not really performance hungry; Postgresql itself does most of the heavy lifting.  I've been using PQexec up until now which takes a single string.c_Str(), but have discovered that when updating and inserting this leaves me wide open to SQL injections so am having to change to PQexecparams which takes a string with placeholders as the SQL statement and a char ** array for the values.  Thankfully I only have one class that does all my SQL updating.  My inserts however seemed too trivial to write a class for so are all over the place (ahh well; that is another lesson learned!).  My big concern was that I was creating and deleting my array correctly as up until now I have done very little with char ** and my program is a posh ncurses terminal front end which when finished could be running on thin clients for weeks or months on end so I need to stay clear of memory leaks.

  • Nurlan

    Hello,
    Alex
    I have a question about range of arrays.\
    the below program is correct;
    a)int *array=new int[5];
    for(int i=0;i<5;++i)
    std::cin>>array[i];

    for(int j=0;j<5;++j)
    std::cout<<array[i]<<' ';
    b)
    in below program array's range is not given properly. So, here should be i<5, not i<=5 in loop.

    int *array=new int[5];
    for(int i=0;i<=5;++i)
    std::cin>>array[i];

    for(int j=0;j<=5;++j)
    std::cout<<array[i]<<' ';
    How the program works with 6 integers, where as it only allocated for 5 memory only, but if we allocate 7 memories it gives error, not not 6 memories. Actual dynamically allocated memory are 5. Could you clarify this? Why does it give error when it allocates 7 memory, but not for 6 memory, whereas it only has 5 allocated  memories.

    • Alex

      I don't follow you. Can you give me an example of a case where it gives an error?

      • Nurlan

        Hello Alex,
        I was sick,sorry for delaying the reply and improper asked question.
        what is the difference between 1'st and 2nd programs?
        Why I am asking this because in below programs 5 integer are only allocated on both programs, but it gives permission to allocate 6 integers without compilation error in 2nd program.Could you explain why 2nd program doesn't give error. what is the advice of yours? Which one is right program?

        1)int *array=new int[5];
        for(int i=0;i<5;++i)
        std::cin>>array[i];

        2)int *array=new int[5];
        for(int i=0;i<=5;++i)
        std::cin>>array[i]; //Is this wrong program? if it is wrong why does'nt give error.

        Thanks in advance!

        • Alex

          The second program is wrong, as it walks off the end of the array and accesses memory that does not belong to the array. The results of that last access will be indeterminate.

          There's no error given because the compiler can't detect this type of problem, and operator[] doesn't do any bounds checking at runtime to ensure the index is valid.

          If you were to use an array that had bounds checking (e.g. std::array using the get() member function (which does bounds checking)) then the second program would error at runtime.

  • Dohn jose

    Hi Alex,

    I have one querry from this statement "Note that because this memory is allocated from a different place than the memory used for fixed arrays"

    Please see the below code

    1.  I understanding is like this "memory allocated for a dynamically created array is from differnt place of the RAM< not in a sequence" is my understanding is correct ?

    2. if my understating is correct, how the content of my dynamically created array printed using pointer increment like

    3. I am able to print the array content using pointer increment, but i am getting unexpected result when I write data to the array using pointer increment like

    • Alex

      The memory is still allocated as a single block (so the elements of the array are laid out sequentially), it just comes from a different memory pool.

  • Tobias

    Hi,

    do all the following statements delete (release the storage of) the dynamically allocated array?

    In other words, can I delete a dynamically allocated array by deleting any pointer pointing to any of the elements of the array?

    • Alex

      1) Trying to delete an array by using a pointer to something other than the start of the array will result in undefined behavior.
      2) This is fine. otherPtr will have the same address as ptr, so you can delete either one.

  • Satwant

    I dint #include <algorithm> for quiz(for std::swap)
    My program still worked .
    Output was correct with algorithm header and without also.

    • Alex

      Your compiler or another header may have included it for you.

      Best practice is to include all of the headers your program needs to run. So you should include it, even if you don't technically need to for your particular compiler.

  • Nurlan

    Hello,
    Alex
    1)My question is about dereference on std::string data type when we dynamically allocate it.
    In C language we were tought as below.
    Example:
    int main()
    {
      char *string1="good";
    printf("%s",string1);
    puts(string1);// it works as well
    return 0;
    }
    as you see here string1 is a pointer to string, it is also the name of string. Therefore, we do not need to use indirection operator *here.
       But in C++, it includes as a part of the standard library.So, it is  an independent data type in it.As an independent data type it should be treated not like as a name of string, rather pointer to string(when we dynamically allocate). am I right?
    These below program works well.if you dont derefenciate on input and output it gives error.My above thoughts are right in this case?if not, why does it give error ?
    Please, Could you clarify them? May be i am totally wrong here- a bit confusion)).
    #include<string>
    #include<iostream>
    int main()
    {
         std::string *str=new std::string;
        std::cout<<"Enter a full namen";
        std::getline(std::cin,*str);//i am talking about this *str-input
        std::cout<<*str;//i am also talking about this *str-output
        
        return 0;
    }

    //=====================================================
    2) when i try to dynamically allocate C-style string and input with white space- this doesn’t wait for user input and obviously we can’t talk about output.
    i have tried in this way:

    #include<string>
    #include<iostream>
    int main()
    {  
           std::cout<<"Give the length of arrayn";
        int length;
        std::cin>>length;
           char *array=new char[length];
        std::cout<<"enter a stringn";
             //std::cin>>array;// it works well.

         std::cin.getline(array,length-1);//but, it does’t wait for user input
        
        
          std::cout<<array;

    return 0;
    }
    I don’t know, may be we don’t have to dynamically allocate the C-style strings with whitespace. The problem - it doesn’t work with whitespace, vice versa it works (without whitespace). Please advise me on how to fix it.
    Thanks in advance!

    • Alex

      In your C program, you're setting a pointer to a char array. You don't need to dereference this because printf and puts know that a char pointer should be treated as a C-style string.

      In the C++ version with std::string, std::string is an object. You need to dereference the pointer because you want the actual std::string object, not just a pointer to it.

      2) In C++ you can't allocate a fixed array with a variable length. You have to dynamically allocate fixed arrays if the size isn't known at compile time.

      But you're better off using std::string anyway.

      • Nurlan

        Hi Alex, sorry for keep asking you. this topic a bit tricky for me.
        I have written thes codes. As you quoted:

        >2) In C++ you can’t allocate a fixed array with a variable length. You have to dynamically allocate fixed arrays if the size isn’t known at compile time.

        Is below program considered to be dynamically allocation on fixed char array? if the size isn't known at compile time  
        //==================================================================
        int main()
        {
          
           char *ch=new char;//

           std::cout<<"enter a string\n";
           std::cin.getline(ch,255);
           std::cout<<ch<<'\n';
           delete[]ch;
           ch=nullptr;//c++11 is accepted
            std::cout<<" after null pointer:"<<ch;
        }

        if it is not correct Could you give me an example, please. I know what you said that std::string is better off.Anyway i want to clear this misunderstanding.Since yesterday i have been searching in internet. I could not find proper answer.

        In previous reply you said I can't allocate a fixed array with a  variable length even though i wrote with "new" operator.
        ex:
        char *array=new char[length];

        so, "new" operator doesnt make any sense here?
        is it not considered to be dynamically allocation on fixed char array?

        One drawback is here, what i understood - we can't write whole string with whitespace.
        For ex:
        #include<iostream>
        int main()
        {
           std::cout<<"enter the length of string\n";
           int length;
           std::cin>>length;
           char *ch=new char[length];
           int i;
           for(i=0;i<length;i++)
           std::cin>>ch[i];
             std::cout<<ch;
          
              delete[]ch;
           ch=nullptr;//c++11 is accepted
        }

        • Alex

          When I said, "You have to dynamically allocate fixed arrays if the size isn’t known at compile time.", I meant to say, "You have to dynamically allocate arrays if the size isn’t known at compile time." (removed the word "fixed").

          To be clear, you can't do this:

          You can do this:

          I'm not sure what you mean when you say you can't write the whole string with whitespace.

  • Azik

    Hi Alex,
    Why in this post, you indicated: "Note that because a dynamic array does not know the length of the array it points to, a dynamic array won’t work inside a for each loop. Pity, that."

    But in the quiz you have used for loop?

    • Alex

      A for-each loop is different than a for loop. You can't use for-each with dynamic arrays, but you can use for loops, if you happen to know how long the array is.

  • Jasper

    Hi! In the solution for the quiz, shouldn't there be #include<algorithm> or #include<utility> (for C++11) to include std::swap? Also, unrelated follow up question because I'm curious; I'm assuming none of the C++ headers cause problems with each other (like <utility> and <cmath>) so why aren't they all automatically included? Is it for performance reasons? Also, thanks again for the amazing tutorials!

    • Alex

      Yes, the include was missing. I've added it. The C++ headers aren't included by default for performance reasons. It would take the compiler a long time to parse through all of them.

  • BenCampos

    Hi Alex;
    First thank you for your great job in this site.
    Maybe you don't know but you are helping a lot of people in the world to learn C++ using your site. Here in Brazil it is considered the best one.

    I read your tutorial about dinamically alocated memory and I wrote this code.

    It does not run at all, but when I cut off the second part it runs only if the first matrix is squared: (3x3 or 10x10 it runs ok) ,
    But if it is rectangular (2x5 or 6x3) it crashes.
    Could you help me to undestand why?

  • Avijit Pandey

    Hi Alex!Your tutorials are helping me a lot
    I have a confusion
    In the quiz program, what is the significance of deleting the array at the end of the program, wouldn't the memory allocated for the string get returned to the operating system when the program closes?If not, what will happen when the program closes?

    • Alex

      Modern operating systems will clean up all memory allocations from a program that is terminating. However, doing the deletions yourself is considered best practice, and helps form the habit of deleting memory you allocate so you don't end up with memory leaks when your program isn't terminating immediately.

  • Elchin

    Dear Alex,

    First of all thanks for the great tutorial!

    I am doing your quiz task and encountered small confusion.

    my setNames() function supposed to take pointer to a string array (dynamically allocated) and its length as an argument, then loop through each element and set some std::string value to it.

    However, upon launch the input becomes only possible after first iteration passes.
    So when i = 0 input is being skipped for some reason, as if there is some condition check that tells compiler to skip that line and then when i = 1 input becomes available and everything works as it supposed to work

    My output looks like that:

    Debugging shows some weird values that are unclear to me yet, so I really have no idea what’s happening…

    I am using Visual Studio 2016

    • Elchin

      I solved the issue by simply replacing std::getline() with std::cin.
      As I learned from googling the issue, the problem occurs due to getline's "sensitivity" when handling symbols that are already in cin buffer.

      Apparently, I have another function getNumbers() that also asks for user input.

      I assume, that when the number is entered, '\n' is being saved to the buffer somehow.
      And when I call setNames() getline intercepts this '\n' from the buffer and simply accepts it as user input during first iteration.

      I will try to clean the buffer right after first input request ans see if it works, when I reach home.

  • Sam

    Hi!
    In the part "Initializing dynamically allocated arrays" You should probably use the words "uniform initialization" for consistency of the text style.

  • Christopher

    In the quiz, why does the names array have to be a pointer? I really am very confused with all these pointers, they seem very useless to me.

    • Alex

      You have to use a pointer because C++ won't allow you to create an fixed-size array with a non-const-at-compile-time size. Since we're reading the number of array elements to allocate from the user, we need to dynamically allocate an array. Since the memory for the array returned by operator new doesn't have a name, we have to assign a pointer to it so that we can access it somehow.

Leave a Comment

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