Skip to content
View in the app

A better way to browse. Learn more.

LCPDFR.com

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

[C++] A very weird problem regarding Array sorting using for(;;;) loops

Featured Replies

Hiya!
So, for a Computer Science class assignment, there's a question about the user inputting 2 separate arrays, then the PC has to sort them; 1 ascending, 1 descending. Then merge them into a third array & sort ascending. Then, output all 3 arrays.
Since we haven't learnt anything aside from simple loops (for, while, do-while), I used a for loop (even tho I researched & figured out how to use std:sort).
 
I made a program for the user to input 2 separate arrays & sort 1 in ascending, & another in descending & to output them both.
Long story short, it didn't work & I couldn't figure out why. So, I created another program to just input 1 array & sort it. It didn't work either.
So, to debug, I put it to output everything as it processes it. And by magic, it worked perfectly. Then, by slowly removing each debug line, I was left with 2 cout lines that, if removed, screws up the sorting.
 
The program:-

#include <iostream.h>
#include <conio.h>

void main()
{
 clrscr();
 int array[5], temp1, temp2, i=0, y=5;
 cout<<"Enter the 5 array numbers to be sorted: ";
 for(;i<5;i++)
  cin>>array;
 for(y=5;y>=0;y--)
 {
  for(i=0;i<5;i++)
  {
   if(array<array[i+1])
   {
    temp1=array;
    temp2=array[i+1];
    array=temp2;
    array[i+1]=temp1;
   }
   cout<<"nSorted array number "<<i<<"'s value is: "<<array;
   cout<<"nSorted array number "<<(i+1)<<"'s value is: "<<array[i+1];
  }
 }
 cout<<"nnThe sorted array is: ";
 for(i=0;i<5;i++)
  cout<<array<<" ";
 getch();
}

 

The cout lines in question are:-
 


   cout<<"nSorted array number "<<i<<"'s value is: "<<array;
   cout<<"nSorted array number "<<(i+1)<<"'s value is: "<<array[i+1];

 
I know, the program could've been done in a better way. But I want to figure that out myself.
I'm going to be asking my teacher why this happens next week (school is currently closed for us here), but in the mean-time, I wonder if anyone here has a thought on why this happens.
(This program has been written, compiled, & run using Borland C++ v5.02)

Edited by Rocking_Star101

If my post made you laugh (or giggle) in any way, smash that blue grey "Like this" button & like it :smile:

If my answer to your Support Thread fixed your problem, please Vote it up by clicking the ^ (up) arrow to the left of my name.

  • Management Team

Only had a quick look, but it's probably because you exceed the array bounds when doing i+1, since you essentially do array[5] which does not exist. You access invalid memory here!

 

Also what I noticed:

You don't check for integer bounds, i.e. entering a large number breaks the whole thing (because cin will just overwrite memory without checking bounds)

clrscr is compiler-specific

 

A better solution might be:

	int array[5], temp1, i = 0, y = 0;
	cout << "Enter the 5 array numbers to be sorted: ";
	for (; i<5; i++)
		cin >> array;
	for (i = 0; i< (5 - 1); i++)
	{
		for (y = (i + 1); y < 5; y++) 
		{
			if (array < array[y])
			{
				temp1 = array;
				array = array[y];
				array[y] = temp1;
			}
		}
	}
	cout << "nnThe sorted array is: ";
	for (i = 0; i<5; i++)
		cout << array << " ";
	_getch();

Dynamic number count:


int compareAscending(const void * a, const void * b)
{
    return (*(int*)a - *(int*)b);
}

int compareDescending(const void * a, const void * b)
{
    return (*(int*)b - *(int*)a);
}

int _tmain(int argc, _TCHAR* argv[])
{
    const int numbersCount = 8;
    int* array = new int[numbersCount], temp1, i = 0, y = 0;
    printf("Enter the %d array numbers to be sorted: n", numbersCount);
    for (; i < numbersCount; i++)
        cin >> array; // Better to read single characters or use std::string as buffer, as you have no boundary check here!
    qsort(array, numbersCount, sizeof(int), compareDescending);
    cout << "The sorted array is: n";
    for (i = 0; i < numbersCount; i++)
        cout << array << endl;
    delete[] array;
    _getch();

}

Please do not PM me unless really necessary (knowing you helps). If you think you need my attention in a topic, tag me.

  • Author

-snip-

 

Oh yes, of course! *smacks forehead with open palm*

Thanks a bunch for that & the cleaner program.

clrscr became almost a habit of sorts, since we use Turbo C++ in our school & that intro box when running a program irritates me :tongue:

I don't completely understand the Dynamic number count program, but I think I got the jist of it & am saving it for future figuring-out & reference.

One question: Any idea as to how the cout lines somehow patched (or more like, Band-aided) the fault in my program?

If my post made you laugh (or giggle) in any way, smash that blue grey "Like this" button & like it :smile:

If my answer to your Support Thread fixed your problem, please Vote it up by clicking the ^ (up) arrow to the left of my name.

  • Management Team

I don't completely understand the Dynamic number count program, but I think I got the jist of it & am saving it for future figuring-out & reference.

One question: Any idea as to how the cout lines somehow patched (or more like, Band-aided) the fault in my program?

 

No problem! I just wanted to show that it is generally (not always, e.g. fixed size buffers) bad pratice to use a constant number in multiple lines instead of moving it to a variable. Hence why I made the memory allocation dynamic.

 

I'm not sure, but I guess it was rather due to the invalid/random memory than an actual relation. I do appreciate that you learn a real language at University though and don't dive into a higher-level one where you will never learn/know about memory allocation etc.

Please do not PM me unless really necessary (knowing you helps). If you think you need my attention in a topic, tag me.

Accessing uninitialized or invalid memory tends to lead to weird results; it means that changes to your program that seemingly shouldn't affect anything actually change the result of running it. Those are among the most annoying kind of errors to debug (and have the potential to be the worst kind, the "heisenbug", which disappears when you attempt to isolate it by doing things like running in a debug environment).

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Recently Browsing 0

  • No registered users viewing this page.

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.