2014-10-20 49 views
1

我是一个初学者,所以我很抱歉,如果这是真的愚蠢的问题/问题。 我的任务是从输入文件中打印出一个动态数组。我试着用Google搜索,发现了一些类似的问题......但答案都像“使用矢量”等,但我们还没有学到这些。也有人说,必须使用一个函数。这是我想出了:动态数组从输入文件

#include <iostream> 
#include <fstream> //file input 

using namespace std; 

int *out(int *arr, int siz){ 

    arr = new int[siz]; 
    for (int i = 0; i < siz; i++) { 
     cout << arr [i] << " "; 
    } 
    return arr; //this should print out the array later??? 

} 

int main(){ 

    int siz; 
    int *arr; 

    ifstream inf ("input.txt"); 
    inf >> siz; // 
    for (int i = 0; i < siz; i++) { 
     inf >> arr[i]; 
    } 
    inf.close(); 


    cout << "This array contains following elements: "; 
    *arr = *out(arr, siz) ; 

    delete[] arr; 
    return 0;} 

所以,它并没有给与开发 - C++任何错误,但是当我尝试运行它,它崩溃。我试着调试它,然后它给了我“分割错误”或类似的东西。当然,我用google搜索了一下,这些指针肯定有问题,对吧?你能帮我吗?谢谢。

+2

某物利用更近期的和C你的主要需求使用ARR来填充元素之前分配ARR ++ 11符合标准的编译器(例如[GCC](http://gcc.gnu.org/)),并编译所有警告和调试信息('g ++ -Wall -g')。然后使用[std :: vector](http://en.cppreference.com/w/cpp/container/vector)。学习如何使用调试器**('gdb') – 2014-10-20 10:57:13

+0

除此之外,你的部分代码没有任何意义(具有返回值的东西......) – deviantfan 2014-10-20 10:58:19

+1

你正在读取你的文件到一个unalloacated内存'改编”。首先分配你的记忆,然后阅读 – 999k 2014-10-20 10:58:21

回答

1

当arr尚未分配或初始化为有效数组时,您正试图访问arr。 所以,这里的更改后的版本:

#include <iostream> 
#include <fstream> //file input 

using namespace std; 

void out(int *arr, int siz){ 
    for (int i = 0; i < siz; i++) { 
     cout << arr [i] << " "; 
    } 
} 

int main(){ 

    int siz; 
    int *arr; 

    ifstream inf ("input.txt"); 
    inf >> siz; 
    arr = new int[siz]; // added 
    for (int i = 0; i < siz; i++) { 
     inf >> arr[i]; 
    } 
    inf.close(); 

    cout << "This array contains following elements: "; 
    out(arr, siz); 

    delete[] arr; 
    return 0; 
} 
1

arr未初始化的指针。 在将数据读入arr之前,请执行arr = new int[size];

+0

我derped @deviantfan – Yann 2014-10-20 11:04:41

+0

是的,我不知道为什么我这么想。我正在环顾四周,看看可能导致我相信的事情。 – Yann 2014-10-20 11:09:51

+0

这是一个公平的问题,在这种情况下,这不是一个有效的论点。 C在声明期间不允许数组大小的非const整数。 – Nard 2014-10-20 11:11:53

0

您还没有将内存分配给阵列,您可能需要使用malloc。读完数组的大小后,分配内存。

inf >> siz; 
arr = malloc(siz * sizeof(*int)); 
//Rest of program 

//delete[] arr; <- you use this with the new keyword 
free(arr); //Use 'free' with malloc 
return 0; 
0

我想你想可能是这样

#include <iostream> 
#include <fstream> 
int main(){ 
    int siz(0); 
    std::ifstream inf ("input.txt");//Assume that the input file and this file are in the same folder 
    inf >> siz; //Assume that the first number in input file is the size of array 
    int *arr=new int[siz]; 
    for (int i = 0; (siz-i)&&inf ; ++i) { 
     inf >> arr[i]; 
    } 
    inf.close(); 

    std::cout << "This array contains following elements: "; 
    for (int i = 0; siz -i ; ++i) { 
     std::cout << arr [i] << " "; 
    } 
    delete[] arr; 
    return 0; 
}