I'm working on a program that will get a list of words from the user and rearrange it in alphabetical order. So far it works but I think it may have some memory issues because I was testing an alternative way of asking the user how many arrays will be needed other than dynamic memory.

Here is the code:

#include<string>

using namespace std;

int main()
{
    int n; //Used to set the number of arrays of MiString and MiNewString.
    cout << "How many words do you want the list to contain? ";
    cin >> n;

    string MiString[n], MiNewString[n], Temp; //This does work but there may be issues I'm unaware of.
    int i, ii, _Place;

    for (i=0; i<n; i++) //Get the list from the user.
    {
        cout << "Input a word: ";
        cin >> MiString[i];
    }

    for (i=0; i<n; i++) //Alphabetize list
    {
        for (ii=0, _Place=0; ii<n; ii++)
        {
            if (MiString[i] > MiString[ii]) {_Place ++;}
        }
        MiNewString[_Place] = MiString[i];
    }

    cout << "\nYour alphabetized list is:\n";

    for (i=0; i<n; i++) \\Print new list
    {
        cout << MiNewString[i] << "\n";
    }
return 0;
}

If you see any problems with this please tell me.

When declaring an array, the length must be a constant known at compile time. What you are using here is a language extension for C compilers that allows a "variable-length" array to be defined statically. The downside is that your solution will be non-portable and non-standard as not all compilers support this extension. See http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html for example.

A much better (C++) solution would be to move away from C-Style arrays and use a container class like 'vector'.

This will also allow you to use std algorithms like std::sort to sort the vector

Thanks I'll try that.

I'd also like to point out that it's very bad style to declare counter variables outside the for loop, unless you actually need the value the loop stopped at.

@Aranarth

Its a C- style approach. When we are program in C, all the variables have to be declared at the start of the function block

His approach isn't C-Style as the int i, ii; is not at the start of a scope block.
He does re-use the 'i' in two for loops, which is asking for confusion.

Anyway Ral78 what they are trying to point out is that it is good practice to make a variable's scope as short as possible (do you know what a 'scope' is?). So it is better to write code like:

for( int i = 0; i < n; ++i )
{
   // we can use i here
}
// here we can _not_ use i anymore

for( int i = 0; i < n; ++i )
{
  // Here we can use the new i again
}
// Nope, can't use i anymore

@ thelamb
Thanks I've forgotten about that. =)