2014-10-20 46 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; 
}