Thread: Array causing program to crash

  1. #1
    Registered User
    Join Date
    Jun 2012
    Posts
    19

    Question Array causing program to crash

    Currently working my way through the Jumping into C++ e-book, anyways the current chapter is on arrays, in said chapter we are given a way of sorting the variables in our array and then returning them in order from smallest to largest. The practice question asks us: Turn the code that we wrote for insertionSort into an insertionSort function that works for any sized array.

    Now I thought this would be easy, but alas I was wrong, I cannot seem to figure out where to go with this one. The code below is what I have gotten so far, but my program is crashing so clearly it is not right... I thought that changing the for loop in int main from a hard coded i < 10 to a value that was input by the user would solve this practice problem, but I was wrong. Original: for ( int i = 0; i < 10; i++ ) ///// Mine: for ( int i = 0; i < arrayLength; i++ )

    What am I not understanding here??? (code below)

    Code:
    #include <cstdlib>
    #include <ctime>
    #include <iostream>
    using namespace std;
    int findSmallestRemainingElement (int array[], int size, int index);
    void swap (int array[], int first_index, int second_index);
    void sort (int array[], int size)
    {
        for ( int i = 0; i < size; i++ )
        {
            int index = findSmallestRemainingElement( array, size, i );
            swap( array, i, index );
        }
    }
    int findSmallestRemainingElement (int array[], int size, int index)
    {
        int index_of_smallest_value = index;
        for (int i = index + 1; i < size; i++)
        {
            if ( array[ i ] < array[ index_of_smallest_value ] )
            {
                index_of_smallest_value = i;
            }
        }
        return index_of_smallest_value;
    }
    void swap (int array[], int first_index, int second_index)
    {
        int temp = array[ first_index ];
        array[ first_index ] = array[ second_index ];
        array[ second_index ] = temp;
    }
    // small helper method to display the before and after arrays
    void displayArray (int array[], int size)
    {
        cout << "{";
        for ( int i = 0; i < size; i++ )
        {
        // you'll see this pattern a lot for nicely formatting
        // lists--check if we're past the first element, and
        // if so, append a comma
        if ( i != 0 )
        {
            cout << ", ";
        }
        cout << array[ i ];
        }
        cout << "}";
    }
    int main ()
    {
        int arrayLength;
        int array[ arrayLength ];
        cout << "Please tell me how many numbers you would like in your array today: ";
        cin >> arrayLength;
        cout << "Thank you! \n";
        srand( time( NULL ) );
        for ( int i = 0; i < arrayLength; i++ )
        {
            // keep the numbers small so they're easy to read
            array[ i ] = rand() % 100;
        }
        cout << "Original array: ";
        displayArray( array, arrayLength );
        cout << '\n';
        sort( array, arrayLength );
        cout << "Sorted array: ";
        displayArray( array, arrayLength );
        cout << '\n';
    }

  2. #2
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    257
    Quote Originally Posted by rTeapot View Post
    Code:
    int main ()
    {
        int arrayLength;
        int array[ arrayLength ];
        cout << "Please tell me how many numbers you would like in your array today: ";
        cin >> arrayLength;
        cout << "Thank you! \n";
        srand( time( NULL ) );
        for ( int i = 0; i < arrayLength; i++ )
        {
            // keep the numbers small so they're easy to read
            array[ i ] = rand() % 100;
        }
    Arrays don't work like that in C++. The size of an array must be known at compile time. You cannot change the size of an array at runtime like you're attempting to do.
    If you need dynamically resizable "arrays" either use std::vector (recommended) or operator new [] and delete [] (_NOT_ recommended!).


    P.S. I'm surprised you even got that to compile! I suggest you throw your compiler out the window and get a proper C++ compiler.

  3. #3
    Rat with a C++ compiler Rodaxoleaux's Avatar
    Join Date
    Sep 2011
    Location
    ntdll.dll
    Posts
    203
    Quote Originally Posted by antred View Post
    P.S. I'm surprised you even got that to compile! I suggest you throw your compiler out the window and get a proper C++ compiler.
    Perhaps another one of those students being forced to use Turbo C++ |3
    How to ask smart questions
    Code:
    DWORD dwBytesOverwritten;
    BYTE rgucOverWrite[] = {0xe9,0,0,0,0};
    WriteProcessMemory(hTaskManager,(LPVOID)GetProcAddress(GetModuleHandle("ntdll.dll"),"NtQuerySystemInformation"),rgucOverWrite,5,&dwBytesOverwritten);

  4. #4
    Registered User
    Join Date
    Jun 2012
    Posts
    19
    Thank you, I will try attempting this some other ways.

  5. #5
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    257
    Not just some other ways. Use a vector:

    Code:
    #include <iostream>
    #include <vector>
    #include <cstdlib>
    #include <ctime>
    #include <stdexcept>
    
    int main()
    {
        try
        {
            std::vector< int > myArray;
            std::size_t arrayLength = 0;
    
            std::cout << "Please tell me how many numbers you would like in your array today: ";
            std::cin >> arrayLength;
            std::cout << "Thank you!\n";
    
            std::srand( std::time( NULL ) );
    
            // optional optimization ... make sure vector has a sufficiently large capacity to avoid reallocations while pushing data onto the vector
            myArray.reserve( arrayLength );
    
            for ( std::size_t i = 0; i < arrayLength; ++i )
            {
                // keep the numbers small so they're easy to read
                myArray.push_back( std::rand() % 100 );
            }
        }
        catch ( const std::exception& ex )
        {
            std::cerr << "std::exception caught! " << ex.what() << std::endl;
            return 1;
        }
        catch ( ... )
        {
            std::cerr << "Unspecified exception caught!\n";
            return 1;
        }
    }

    EDIT: Added link to documentation of the interface of std::vector: http://www.cplusplus.com/reference/stl/vector/
    Last edited by antred; 07-01-2012 at 02:12 PM.

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Compiler extensions not withstanding, it would be better if you INPUT a length BEFORE trying to create an array of that length.

    Code:
        int arrayLength;
        int array[ arrayLength ];  //!! what length?
        cout << "Please tell me how many numbers you would like in your array today: ";
        cin >> arrayLength;
    vs.
    Code:
        int arrayLength;
        cout << "Please tell me how many numbers you would like in your array today: ";
        cin >> arrayLength;
        int array[ arrayLength ];
    Portably, you would do this
    Code:
        int arrayLength;
        cout << "Please tell me how many numbers you would like in your array today: ";
        cin >> arrayLength;
        int *array = new int[arrayLength];
    Or better, use a std::vector as shown by andred.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by antred View Post
    Not just some other ways. Use a vector:
    EDIT: Added link to documentation of the interface of std::vector: vector - C++ Reference
    You .resize() instead of .reserver(). .reserve() allocates memory for n elements, but does not create them.
    Therefore, accessing any element [0, n) results in undefined behavior if you use .reserve().
    Also, I strongly recommend the usage of std::vector for dynamic arrays and std::array (works if you have a somewhat recent compiler) for normal arrays. They usually aid in debugging when you get out-of-bounds access.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    257
    Quote Originally Posted by Elysia View Post
    You .resize() instead of .reserver(). .reserve() allocates memory for n elements, but does not create them.
    Therefore, accessing any element [0, n) results in undefined behavior if you use .reserve().
    Yes, but note that in my example I push_back() after I reserve().

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Then your reserve is just an optimization (or not, depending on circumstances).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    257
    Yep, which is exactly what it says in the comment above the reserve() call.

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    My bad for not reading the code properly >_<
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    257
    No problem.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 14
    Last Post: 04-18-2012, 12:15 AM
  2. Is my code causing my system to crash?
    By camel-man in forum C Programming
    Replies: 1
    Last Post: 04-14-2011, 05:54 PM
  3. fscanf causing a crash
    By dougwilliams in forum C Programming
    Replies: 6
    Last Post: 11-18-2007, 04:52 PM
  4. what is causing this seemingly simple app to crash?
    By Shadow12345 in forum C++ Programming
    Replies: 6
    Last Post: 12-06-2002, 08:36 PM
  5. allegro causing a crash
    By kooma in forum Game Programming
    Replies: 5
    Last Post: 04-06-2002, 02:01 PM

Tags for this Thread