2

I am trying to learn C++, arrays and pointers. I decided to implement the insertion sort algorithm. So, here is my code and my wrong output. What should I do to correct it? Can you please tell me what is my mistake and what should I avoid if it is a common error?

My code:

// InsertionSort.cpp

#include "stdafx.h"
#include <iostream>

int DeclareAnInteger();
int* DeclareAndShowTheArray(int n);
int* InsertionSort(int *A, int n);

int main()
{

   int n = DeclareAnInteger();
   int *A;
   A = DeclareAndShowTheArray(n);
   int *B;
   B = InsertionSort(A, n);

   system("PAUSE");
   return 0;
}

int DeclareAnInteger()
{
   int n;
   std::cout << "Please enter a positive integer n: ";
   std::cin >> n;
   return n;
}

int* DeclareAndShowTheArray(int n)
{
   int *A;
   A = (int *)alloca(sizeof(int) * n);
   for (int i = 0; i < n; i++)
   {
      std::cout << "Please enter the value of A[" << i + 1 << "]: ";
      std::cin >> A[i];
   }
   std::cout << "The unsorted array is: ";
   for (int i = 0; i < n; i++)
   {
      std::cout << A[i];
      std::cout << "\t";
   }
   std::cout << "\n";
   return A;
}

int* InsertionSort(int *A, int n)
{
   int k;
   //int *A = new int[n];
   for (k = 1; k < n; k++)
   {
      int key = A[k];
      int m   = k - 1;
      while (m >= 0 & A[m] > key)
      {
         A[m + 1] = A[m];
         m        = m - 1;
      }
      A[m + 1] = key;
   }
   std::cout << "The sorted array is: ";
   for (int i = 0; i < n; i++)
   {
      std::cout << A[i];
      std::cout << "\t";
   }
   std::cout << "\n" << std::endl;
   return A;
}

My output: enter image description here

1
  • 9
    Please don't use pictures to paste some text. Just paste the text itself. Commented Jan 17, 2015 at 17:23

1 Answer 1

9

This here is a big problem:

A = (int *)alloca(sizeof(int) * n);

The alloca function allocates on the stack, and it will be lost when the function returns which gives you a stray pointer and undefined behavior when you dereference this pointer.

If you're programming C++ then use new, if you program C then use malloc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.