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:

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).

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.


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

388 comments to 6.9a — Dynamically allocating arrays

  • Matt

    My take on this quiz below.  One question: I forgot to #include <utility>, yet std::swap() still worked for me. I have precompiled headers turned off (if that makes a difference).  Has swap() been baked into <string> or <iostream> or is this a side effect of using Visual Studio Community 2017?


    • * Line 77: Initialize your variables with brace initializers. You used copy initialization.
      * Line 15, 19: Don't pass 32767 to @std::cin.ignore. Pass @std::numeric_limits<std::streamsize>::max().

      @<iostream> or @<string> are including @<utility>. This is not standard. If you use something, include its header.

  • Matvey Kiselyov

    What does this mean?

    int **arr = new int*[size];

    And how it works in steps.

  • Z_Doctor

    So I tried using the following code in Visual Studio and no errors happened when I ran the program

    The output is as expected. Was an error supposed to be thrown, or did I misunderstand what you meant that it's not supported in c++11, or perhaps later versions support it?

    • Hi!

      There's nothing wrong with this code. The closest thing I can think of is

      This is illegal.
      Array creation from string literals is allowed.

      • Alex

        Z_Doctor's snippet compiles on Visual Studio, but not on GCC. It fails with error:

        In function 'int main()':
        7:49: error: invalid conversion from 'const char*' to 'char' [-fpermissive]

        • It's a bug in gcc. A bug report has already been filed here in 2016 (And apparently a duplicate, which I can't find). This is the second bug in gcc I encountered, neither of which has been fixed.
          Nothing has changed since, n4800 states

          § (19) A new-expression that creates an object of type T initializes that object as follows:
          (19.1) — If the new-initializer is omitted, [...]
          (19.2) — Otherwise, the new-initializer is interpreted according to the initialization rules of 9.3 for direct-initialization.

          § 9.3.2 Character arrays
          (1) An array of ordinary character type [...] can be initialized by an ordinary string literal [...], or by an appropriately-typed string literal enclosed in braces (5.13.5). Successive characters of the value of the string literal initialize the elements of the array.

          MSVC and clang behave correctly.

  • J


    So originally, I just had "std::sort(namesArray, namesArray + numberOfNames);" in the sortNames function and I included the algorithm library. I switched it because the instructions said to modify the code from lesson 6.4. My code is below.

    It made sense to me in the previous lessons when we sorted the integer values, but how exactly does it work with sorting strings? Is it comparing the ASCII values of each char behind the scenes?

  • whoon

    May I do the sorting like this instead of the smallestIndex way? This seems to work okay, unless there's something I didn't know was wrong with it :/

  • Mechanic

    You use new[] and delete[] in this lesson for dynamic memory allocation.  In C, malloc(), calloc(), and free() are used.  What is the difference between them? Are there advantages to using one over the other?  Thanks for the tutorials.

    • Alex

      malloc(), calloc(), and free() are C memory allocators and should not be used in C++. new and delete completely replace them, are more type-safe, and provide additional bits of functionality (such as calling constructors) that we cover later on in these tutorials.

  • Hey i wanted to sort with ascii characters for my program but i keep getting these errors and i cant seem to find where im going wrong.

    main.cpp: In function ‘void sortNames(int, int*, std::string*)’:
    main.cpp:19:27: error: base operand of ‘->’ has non-pointer type ‘std::string {aka std::basic_string}’
               strcpy(x, ptr[y]->c_str());  
    main.cpp:21:18: error: lvalue required as left operand of assignment
               (int)x = sort[y];
    main.cpp: In function ‘int main()’:
    main.cpp:81:20: error: variable or field ‘sortNames’ declared void
         void sortNames(length, *sort, *ptr);

    • Hi Bubba!

      * Line 8, 25, 28, 31, 44, 61, 62, 63: Initialize your variables with brace initializers. You used copy initialization.
      * Line 73: Initialize your variables with brace initializers. You used direct initialization.
      * Line 10, 12, 57, 58: Initialize your variables with brace initializers.
      * Line 31, 62, 63, 65, 68, 71: Limit your lines to 80 characters in length for better readability on small displays.
      * Use ++prefix unless you need postfix++
      * Line 73: Remove "void". You only have to state the type at declarations.
      * Line 73: *sort and *ptr return the first element of the array. You need to pass the array itself.
      * Use the auto-formatting feature of your editor

      @ptr is an @std::string*, @ptr[y] is an @std::string. -> is used to access pointers.
      @std::strcpy is used to copy entire strings, not single characters.
      Your program would only compare the first letter, see the hint in the quiz (Line 10-13 are a mess, remove them).

      Feel free to post further questions and your progress.

      • I figured it out by looking at the example, I took a very confusing approach to this but I was having trouble with std::swap(ptr[startIndex], ptr[smallestIndex]);

        I didn't know how the program figured out which one was bigger, one of my friends said they "Overloaded the operators" which is soomething we get into in chapter 9, I was just wondering if I was supposed to understand the selection sort right now.....

  • Matty J

    I started messing around with the sort on strings, putting in names like 'aDZA' and 'addison'

    Even though technically addison alphabetically comes before aDZA (not a real name, but I think you understand what I'm testing), the ASCII in 'D' is less than 'd' so the sort places aDZA before addison. Would there be a way to make all characters have an equivalent value? I.e. 'D' = 'd' when making alphabetical comparisons?

    Also, how does the program know to move to the next character in the string when making a less-than/greater-than comparison for alphabetical sorting? Just an inherent feature in C++?
    I thought it was pretty cool how we don't have to manually string together if/else-if to move from the first character in a string to the next. Now that I'm writing it, it probably has something to do with strings behaving like arrays?

    Just curious, thanks!

  • Rai

    I made this program that randomly generates numbers and removes the odd numbers and then sort out the even numbers. I was reading out std:remove and std::move on a different website.

    How many numbers do you want:
    The numbers generated are:
    Number #1: 58
    Number #2: 6
    Number #3: 4
    Number #4: 91
    Number #5: 99
    Removing odd numbers...
    Sorting out list
    Number #1: 58
    Number #2: 6
    Number #3: 4
    There are 3 even numbers.

    The program works except I can't sort the even numbers out from smallest to largest.
    1. How could I improve this code to be more efficient?
    2. How could I sort the even numbers out? I'm not sure what int *array should be. like neither sortArray(newNum, length) or sortArray(number, length) was working.

    I stuck with std::swap because I don't know how std::sort works. The example on a previous lesson was vaguely explained.
    Any help would be appreciated.

    • * Line 10, 12, 13, 29, 30, 32, 52, 63: Initialize your variables with uniform initialization
      * Line 57: Use ++prefix unless you need postfix++
      * Line 62: number[length] causes undefined behavior. Use number + length
      * Line 63: Rename @q to "i"

      > I don't know how std::sort works

      Update these points. Add a call to @std::sort or @sortArray, even if it's not working. Post input/output and expected output.

      • Rai

        Thanks. I still got no clue about std::sort. I'll probably understand it better when I get to std::array and vector lessons.
        also I believe I forgot to put: delete[] number;

        Fixed the sorting even numbers out using bubble sort method. The selection sort sometimes would make a larger number appear before a smaller one.

      • Rai

        I think I understand sort better. Does std::sort (array[0], array[last number] ) go automatically through every number between array[0] and array[last number] and sort them from lowest to largest?
        I removed void sortArray(int *array, int length) completely and just used

        This did all of the job that sortArray() did in just one line! Pretty cool :D. Just unsure if I used it correctly.

        also in, the example showed

        Does this mean the numbers between myvector.begin()+4 and myvector.end() are being compared. If the first number is smaller than the rest of the number, the first number goes to myvector.begin()+4.

        So the first i would be 26 and it is smaller than all the j: 53, 80, 33, so its sorted first in the list. The next i compared is 33 with all the other j: it is smaller than 53 and 80 but not 26 so appears after 26 in the list in .begin()+5. it carries on until all numbers are i and are compared to every number as j to give 26,33,53,80 ???

        • > I believe I forgot to put: delete[] number
          You did, I forgot to write it down. Good thing you spotted it yourself!

          You used @std::sort correctly. The first parameter is where to start sorting, the second parameter is where to stop sorting (This element is exclusive!) and the last parameter is an optional compare function.
          The example sorts @myvector starting at index 4, ending at the last element. The first 4 elements remain untouched. @myfunction is unnecessary, because @std::sort compares using operator< by default. You only need to pass a function if you want to sort in a different order.

  • cyanoCittaCristata

    to get the sorting function to work properly, i had to check the length of each index i was comparing.
    i noticed no one else mentioned this, so i assumed it must have been some weird "under-the-hood" behavior.
    any ideas?

  • magaji::hussaini

    what about using std::sort

    • Hi!

      @std::sort is preferred over implementing a sorting algorithm manually. Unless you need full control or know that your algorithm is better.

      * Don't use goto
      * Initialize your variables with uniform initializaiton
      * Don't pass 32767 to @std::cin.ignore
      * Line 28-30 can be done in 1 line
      * Line 39: Rename "j" to "i"

      • magaji::hussaini

        Thanks nascardriver,
        but I think I used uniform initialization almost everywhere.
        *@goto:  The code is simple and not a spaghetti style.
                 And if I am to avoid it what is the use of "goto" in programming.

        *@std::cin.getline(32767, '\n') can I get an alternative and a brief
        explanation please.
        *@Please can I get a snippet of line 28-30 in 1 line.
        Thank you very much for your help..

        • > I used uniform initialization almost everywhere
          Line 10. Despite it not making a difference in this case (assuming you're using c++11 or later), initializing all variables helps writing predictable code. Debugging an error caused by uninitialized variables is a pain.

          > goto
          Goto is harder to read than any of the control structures offered by c++.
          The only valid reason to use goto is to break out of multiple loops at once.

          > std::cin.getline
          Pass @std::numeric_limits<std::streamsize>::max() to disable the count check

          > line 28-30 in 1 line

  • Clapfish

    Hi guys,

    I wondered about this part of the solution in the sorting function:

    I added an if condition here so that it would only make the swap if there was a difference:

    Does std::swap do nothing if the parameters are the same, or will it always make a swap (and thus be less efficient if no swap is required)?


    • Hi Clapfish!

      @std::swap doesn't compare the elements before swapping. You'll later learn about operator overloading. @std::swap could cause undesired behavior if it compared the elements first.
      On top of that, depending on the type, it could even be faster to swap the elements than comparing them.

  • Wen

    Hello, I took a few lines code from the solution that I don't understand.
    Why the argument in shortArray is "names" with the parameter of "std::string *array"?
    Is that means the pointer(array) is point to names?
    Because in previous lesson I learnt that names can be decay into pointer and the memory address will be the same as names[0]. But we need to get more input from user and we only have the memory address of name[0]. Can you explain to me about that? Thanks!

    • Hi Wen!

      is equivalent to

      > names can be decay into pointer and the memory address will be the same as names[0]
      It will be the same as &names[0]

      If you don't understand how to get from &names[0] or @names to each element, have another look at lesson 6.8a.

  • Casey

    Would this code be acceptable? It works as intended.

    My thoughts were that we would need to compare the first letter of each string in the array and see if its character code was less (and hence alphabetically smaller than) the next string in the array. Could you tell me why this is not necessary and why

    works? I'm just a little confused on how that comparison works when we are trying to compare only the first letter in the string. Does

    behave like

    and thus

    actually points to the first letter of


    • Hi Casey!

      @std::string::operator< uses @std::string::compare, which performs a lexicographical comparison on each character until a difference is found or the string is over.
      Comparing only the first character is not enough. Take { "Tom", "Tamara" } for example. Your code wouldn't swap the two, even though "Tamara" should be before "Tom".

      * Line 6, 9, 21, 23, 25, 33: Initialize your variables with uniform initialization
      * Line 16: Inconsistent formatting. Use the auto-formatting feature of your editor.
      * You're never deleting @names, resulting in a memory leak.
      * Bubble sort is terribly slow, use @std::sort

  • hoon

    Can you please check my code?

  • feng

    When complier fail,return this:
    In function 'int main()':
    55:17: error: 'nameNum' was not declared in this scope
    #include <string>
    #include <iostream>
    #include <algorithm>

    int getNameNum(int nameNum)
        std::cout << "How many names would you like to enter?" << '\n';
        std::cout << "Your input is: ";
        std::cin >> nameNum;

        return nameNum;

    void sortName(std::string *array, int length)
        for (int startIndex = 0; startIndex < length - 1; ++startIndex)
            int smallIndex = startIndex;
            for(int currentIndex = startIndex + 1; currentIndex < length; ++currentIndex)
                if(array[currentIndex] < array[smallIndex])
                    smallIndex = currentIndex;

    void getPrintName(int x)
        int length = x;
        std::string *name = new std::string[length];
        for (int loop = 1; loop <= x; ++loop)
            std::cout << "Enter name #" << loop << ": ";
            std::cin >> name[loop - 1];
        sortName(name, length);

        for (int time = 0; time < length - 1; ++time)
            std::cout << name[time];

        delete[] name;

    int main()

        return 0;

  • zhou jack


    void sortArray(std::string* array, int length)
        for (int startIndex = 0; startIndex < length - 1; ++startIndex)
            int smallIndex = startIndex;
        for (int currentIndex = startIndex+1; currentIndex < length; ++currentIndex)
            if (array[currentIndex] < array[smallIndex])
                smallIndex = currentIndex;
        std::swap(array[startIndex], array[smallIndex]);

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

        string *name = new string[length];

        for ( int i = 0; i < length; ++i)
            cout << "Enter name#" << i + 1;
            cin >> name[i];

        sortArray(name, length);
        cout << "\nHere is your sorted list:\n";

        for (int i = 0; i < length; ++i)
            cout << "Name    #" << i + 1 << ":" << name[i] << endl;

        delete[] name;

        return 0;

    Why my code is error?

  • Shawn

    The solution on line #8

    Should use length - 1 correct?

  • Hi!
    After going through the tutorial, I have come up with a very weird program.

    So, my guess is that it will crash the operating system (I never ran it). But will it actually crash it?
    Thanks in advance!

    • Alex

      It shouldn't crash the operating system, as programs on modern operating systems run in protected virtual spaces that are designed so they can't take down the OS (only drivers and things that run at higher privilege levels can typically do that).

      Eventually your system will run out of free memory and probably start paging memory out to disk. What happens when the OS has no more memory to allocate is probably OS-specific.

  • Kio

    My 2cents;

    • Hi Kio!

      * Line 6, 12, 16, 19, 34, 42, 43, 45: Initialize your variables with uniform initialization
      * @getInputFromUser: You're returning a reference to a temporary, causing undefined behavior. Your compiler showed a warning. Read compiler warnings and solve them.
      * @print: @array should be const
      * Line 34, 45: Use ++prefix unless you need postfix++
      * Line 34: Use @std::size_t instead of @size_t. Same thing, but @size_t is C, @std::size_t is C++
      * Line 57: Unnecessary variable. Inconsistent use of '\n' and @std::endl
      * Line 61: Don't use @system. If you have to, use @std::system. Use @std::cin.get(). pause is a Windows program, your program will behave differently on other systems.

  • John

    Hi Alex and Nascardriver,
    Could you point out any mistakes I did or where I could improve?

    • Hi John!

      * Line 9, 12, 15, 22, 25, 27, 41: Initialize your variables with uniform initialization
      * Line 11: Use @std::numeric_limits<std::streamsize>::max() instead of 32767. See the documentation of @std::basic_istream::ignore
      * Line 15, 41: Use ++prefix

      Logic is correct

  • Hi Alex and Nascardriver, this is my solution. Could you give me if anything go wrong?

    int main()
        int length;
        std::cout<<"How many names would you like to enter? ";
        std::string *array=new std::string[length];
        for(int i=0;i<length;i++)
            std::cout<<"Enter name #"<<i+1<<": ";
        for(int i=0;i<length-1;++i)
            int smallestIndex=i;
            for(int currentIndex=i+1;currentIndex<length;++currentIndex)
        std::cout<<"Here is your sorted list: "<<std::endl;

        for(int i=0;i<length;++i)
            std::cout<<"Name #"<<i+1<<": "<<*(array+i)<<"\n";

        return 0;

    • Hi!

      Please use code tags (Yellow message below the reply box).

      * Initialize your variables with uniform initialization
      * Use ++prefix unless you need postfix++
      * Use @operator[] to access arrays instead of manually calculating the element

      • Thank you very much nascardriver
        Sorry, but I don't know how to use the code tags. Can you show me how to use the code tags(sorry if my English is bad)

        • [-CODE-]
          Your code here
          Without -

          • My new solution. Is that ok?

  • Terra'Navis

    hi, could someone tell me why when accessing the elements of a dynamically allocated array we dont have to dereference the pointer which points to the dynamically allocated array.

  • Hi

    I keep reusing solutions from other times (sort, swap) maybe I should just put them in a header file (or cpp file) and reuse them like that.

    I believe that the above sort would be great in a full database system of maybe customers or suppliers to run off a list in alphabetical format. Will we cover other sort features associated with DB development?

    • Hi Nigel!

      > maybe I should just put them in a header file (or cpp file)
      The standard library already did that for you. See @std::swap and @std::sort.

      > I believe that the above sort would be great in a full database system of maybe customers or suppliers to run off a list in alphabetical format
      I must disappoint you, but a simple selection sort isn't going to do the job. Database systems are highly optimized in every aspect to be able to handle large tables.

      * Line 8, 9: Use <cstdlib> and <cstdio>
      * Line 15, 31, 34: Uniform initialization

      std::swap -
      std::sort -

  • R310

    Hi Alex and Nascardriver!

    I have been sweating on this quiz and it ended up working, but accidentally! I first did the swap function with a string and forgot a return and I got:
    EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)” mean?

    I am still not sure why it works, and how come the swap function can sort the names I entered (does it compares the first letter? does it go letter after letter?) Does a word look like a single unit in a string array? Did I forget something important?
    Thank you very much for your insights...

    • Hi R310!

      * Don't use "using namespace"
      * Use uniform initialization
      * Use ++prefix unless you need postfix++
      * Read the documentation of the first parameter of @std::cin.ignore

      @std::swap doesn't compare anything. The comparison happens in line 9. @std::string uses a lexicographical comparison.

      std::basic_istream::ignore -
      std::basic_string::operator> -

      • R310

        Hi nascardriver!

        I always forget about using namespace std, since they use it a lot in my class.

        But I read in the comments that swap was a basic function in <utility>. What did they meant?

        BTW, what is 256 refers to in the example you linked [link][/link]?

        // istream::ignore example

        #include <iostream>     // std::cin, std::cout

        int main () {
          char first, last;

          std::cout << "Please, enter your first name followed by your surname: ";

          first = std::cin.get();     // get one character
          std::cin.ignore(256,' ');   // ignore until space

          last = std::cin.get();      // get one character

          std::cout << "Your initials are " << first << last << '\n';

          return 0;

        • > they use it a lot in my class
          You'll see that often in tutorials of all kinds, because it decreases the amount of text and can increase readability on a small scale. In real projects, it's more bad than good, so try to avoid it to begin with and you won't get into a bad habit.

          > swap was a basic function in <utility>
          It is, but it's not comparing or sorting anything. Simplified, @std::swap can be replaced like this

          All it does is swap the values of two variables.

          > what is 256 refers to in the example you linked
          The link wasn't about the example, but about the parameter description, especially the first parameter: "Maximum number of characters to extract (and ignore). If this is exactly numeric_limits<streamsize>::max(), there is no limit".
          @std::cin.ignore will ignore all characters until it finds a space, or until it ignored 256 characters, potentially leaving unwanted content in the input stream.

  • Moein


    when i use

    in the code below, i'm not able to enter the first element to the dynamic array. but with std::cin it's work. i want to use space in my name but with std::cin i can't do this.

    • Hi Moein!

      * Don't use "using namespace"
      * Initialize your variables with uniform initialization
      * Use ++prefix instead of postfix++

      You need to call

      after you're reading from @std::cin.

      • Moein

        How fast did you answer! thanks.

        this statement

        is the same with yours?

        • It's not.

          Yours will ignore up to 32767 characters or up to a '\n' character. This could leave unwanted characters in the input stream, causing undesired behavior.
          Mine will ignore all characters up to a '\n' character.

  • ayush

    an error is there
    33    25    C:\Users\ayush\Documents\cpp\a25.cpp    [Error] cannot convert 'std::string* {aka std::basic_string<char>*}' to 'int*' for argument '1' to 'int sortarray(int*, int)'

    how to resolve this

    and kindly tell me more about this program plzzzzz
    im trying my best to understand this but i cant

    • Idda

      hi ayush,
      in row 5:  int sortarray(int *array,int
      row 26:string *names=new string[length];
      row 33: sortarray(names, length);
      ==> change the datatype in argument in row 5
      I guess it'll solve the problem!
      ...and one more should try to use std::namespace in place of "using namespace std"

  • Rohit

    So I forgot to #include <utility> but the "swap" function still worked. So I checked and apparently in VS 2017, utility is one of the precompiled files in the "External Dependencies" folder in the Solution Explorer pane.

    What confused me though is in a new solution, "string.h" is also there but I still have to #include <string> to get strings to work. Including that adds "string" next to "string.h". Am I correct in thinking that all those files ending in ".h" are ported from c and the ones without .h are c++ versions only?

    I still don't know why I would need to #include <string> if string.h is there and why string.h would be there if i'm required to #include <string> regardless?

    Now the code:
    i know i should use <limits> instead of 32767, but when i gotta do it like 5 times i get lazy haha.
    Also, would it be better to create the array in a different function and then pass the pointer to main or is creating it in main like i did perfectly fine?

    • Alex

      > Am I correct in thinking that all those files ending in ".h" are ported from c and the ones without .h are c++ versions only?

      No, the ones that end in .h are the ones that don't use have their names in the std namespace.

      The headers ported from c generally start with a c (e.g. cassert, cmath, etc...)

    • nascardriver

      Hi Rohit!

      > when i gotta do it like 5 times i get lazy
      Having to write something 5 times is an indicator for having to write a wrapper function for it.

      * Line 35: Initialize strings to "".
      * Line 44: Should be currentName[0], because you only care about the first character.

      Creating the array in @main is fine, you'll learn about alternatives to dynamic arrays in a couple of lessons.

      • Rohit

        Fair point about the wrapper function. what exactly is a wrapper function? would it be kind of like my @printNames function in the sense that i can call it to do the same thing over and over?

        On line 35 i meant to initialize currentName to "\0"; i don't even know how i wrote "\n". guess i'm just so conditioned to type the newline indicator whenever i have a backslash lol

        And good point about line 44. strangely enough though, the comparisons and sorting still work even if i don't use [0]. i guess std::string instinctively knows that comparisons should be defaulted to the first character

        • nascardriver

          A wrapper function is a short function that allows easier access to something else without adding new functionality.
          @std::string::operator< performs a lexicographical comparison on the two strings, but since you only care about one character this is a waste of resources.

  • nascardriver

    Hi Endcity!

    "For standard strings this function performs character-by-character lexicographical comparison."

    * std::basic_string::compare -

  • Endcity

    What does the comparation between 2 string that be used in quiz sollution to sort string array alphabetical work ?

Leave a Comment

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