c ++中的分配错误

时间:2015-03-20 12:28:44

标签: c++

我有以下代码来排序从文本文件中读取的数字。我的文本文件元素必须是这样的:

3 6
6
5
1

第一列中的第一个数字(3)代表我应该排序的元素数量,第二列中的第一个数字代表我必须通过数组发送的最大数量,这里是6。

必须将数字排序为6 5 1

所以这是我的代码,但有错误说"无效的分配大小"以及如何通过数组发送最大值。

我需要帮助。

这是我的代码:

 // Read and Sort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include<fstream>
using namespace std ;
#include<time.h>
#include <string>


int Max ;
int number_of_items;
const int s= 22;
int arr[s];
int n=sizeof(arr)/sizeof(*arr);



class sort{

public:


    int read_file()
    {
    int num = 0;
    int x ; 
    char filename[50];
    ifstream numbersfile ;
    cout<<"Please enter the file name below"<<endl<<"_______________________________________________"<<endl;

    cin.getline(filename,50);

    cout<<"_______________________________________________"<<endl;
    numbersfile.open(filename);

    if(numbersfile.is_open())
    {



    for(int i =0;i<n;i++){
        numbersfile>>arr[i];
        Max=arr[0];
        number_of_items=arr[1];
    }

    }
    else{
        cout<<"Failed To load requierd file"<<endl;
    }

    int arr2[s];
    cout<<"The elements supposed to be sorted are:"<<endl<<endl;
    for(int i =2;i<n;i++){
        numbersfile>>arr[i];
        cout<<arr[i]<<" "<<endl;

    }

      counting_sort(arr2,n);

    return 0 ;}


    int counting_sort(int arr[],int size)
        {

    int n=size;
    int max=arr[0];
    for (int i=1;i<n;i++) {
        if (arr[i]>max) { 
            max=arr[i];
        }
    }

    int *output_array=new int[n];
    for (int i=0;i<n;i++) {
        output_array[i]=0;
    }
    int *count=new int[max+1];
    for (int i=0;i<=max+1;i++) {
        count[i]=0;

    }

    for (int i=0;i<n;i++){
        count[arr[i]]=count[arr[i]]+1;
    }
    for (int i=1;i<max+1;i++) {
        count[i]=count[i]+count[i-1];
    }
    for (int  i=n-1;i>=1;i--) {
        output_array[count[arr[i]]-1]=arr[i];
        count[arr[i]]=count[arr[i]]-1;
    }

    cout<<"The sorted elements are:"<<endl<<endl;
    for (int i=0;i<n;i++) {
        cout<<output_array[i]<<"  ";
    }
    cout<<"\n-----------------------------------------------"<<endl;
    return 0;
}




};

int _tmain(int argc, _TCHAR* argv[])
{
     clock_t t1,t2;
     t1=clock();
     sort s1;
    s1.read_file();

    t2 = clock();
    float diff = ((float)t2 - (float)t1)/1000 ;
    cout <<"The time taken to execute this process is:\n"<< diff<<" Milliseconds." << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:1)

int *count=new int[max+1];
for (int i = 0; i <= max+1;i++) {
    count[i]=0;

}

请注意,此处超出范围,因为您尝试访问最后一个元素count[max+1],因为条件测试中的<=,并且未分配此位置。它应该是这样的:

int *count=new int[max+1];
for (int i = 0; i < max+1;i++) {
    count[i]=0;

}

我建议您仔细检查每个 ,看看您是否未访问某些未绑定/已分配的位置。使用printf或cout进行调试,这非常有用。