2012-07-06 44 views
-5

所以我有一個功能C++基本數組賦值不工作

f(int D[],int A[],int len){ 
    for(int k = 0; k < len; k++) 
     D[k] = A[k]; 

,如果我輸出D的數字是完全錯誤的。函數f被調用Dmain函數中被初始化爲int* D = new int[100000];,並且A都是好的,因爲我在函數中輸出它並且它看起來沒問題。所以......無法理解問題出在哪裏......我也試過memcpy(D+k,A+k,sizeof(int));,它不起作用。

+7

請張貼[SSCCE(http://sscce.org/)。 – ildjarn 2012-07-06 23:53:07

+1

如果你可以爲你的段落設置可讀性的格式,比如突出你的代碼,或者把它放在不同的行上,這將會很有幫助。所有穿插在同一字體中的代碼都很難做出來。這是爲了你自己的利益,你的文章可讀性越強,閱讀它的人越多,並且希望有所幫助:) – Levon 2012-07-06 23:55:23

+0

有沒有理由不能製作'A'和'D''std :: vector's,並且用'D = A;'來複制副本? – 2012-07-07 00:00:59

回答

0

在調試器中運行你的代碼,看看你是否在A[]中沒有垃圾(在函數調用後可能會出錯)。另外我建議你通過參考(如int & D[]const int & A[]const以防止改變A)。

+0

int&D []'和'const int&A []'不是有效的結構 - 你不能有引用數組。 – ildjarn 2012-07-07 00:09:39

+0

A是好的,因爲我打印它,沒關係! – exilonX 2012-07-07 00:09:47

0

從最小的工作示例開始,如下所示,然後將其他代碼集成到其中,直到出現故障。這將是你的錯誤的來源。沒有更多的信息,這幾乎可以告訴你,當您在C++程序中遇到錯誤的值時,您可能會從未初始化的變量中讀取數據。我建議你嘗試在諸如GDB之類的調試器中逐步執行你的程序。

#include <algorithm> 
#include <iostream> 
#include <iterator> 

void f(int D[], const int A[], int len){ 
    for(int k = 0; k < len; k++) 
     D[k] = A[k]; 
} 

int main(int argc, char** argv) { 
    int A[] = { 1, 2, 3, 4, 5 }; 
    int D[5]; 
    f(D, A, 5); 
    std::copy(A, A + 5, std::ostream_iterator<int>(std::cout, " ")); 
    std::cout << '\n'; 
    std::copy(D, D + 5, std::ostream_iterator<int>(std::cout, " ")); 
    return 0; 
} 

除非你有一個很好的理由這樣做,寧願std::vectorstd::array通過原始陣列。不過,學習數組和指針的工作原理是使用它們的好理由。

1

您的循環完美地工作。該問題必須在代碼中的其他位置。

下面是一個例子程序,拷貝三種不同的方式中的數據:一個for循環,memcpystd::copy

#include <algorithm> 
#include <cstring> 
#include <iostream> 
#include <iterator> 

void copy1(int D[], int A[], int len) { 
    for(int k = 0; k < len; k++) 
    D[k] = A[k]; 
} 

void copy2(int D[], int A[], int len) { 
    std::memcpy(D, A, len*sizeof(int)); 
} 

void copy3(int D[], int A[], int len) { 
    std::copy(A, A+len, D); 
} 

int main() { 
    int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
    int *d = new int[10]; 

    std::ostream_iterator<int> out(std::cout, ","); 

    // First, print the initial values 
    std::copy(d, d+10, out); 
    std::cout << "\n"; 

    // Next do the copies and print the values again 
    copy1(d, a, 10); 
    std::copy(d, d+10, out); 
    std::cout << "\n"; 

    copy2(d, a, 10); 
    std::copy(d, d+10, out); 
    std::cout << "\n"; 

    copy3(d, a, 10); 
    std::copy(d, d+10, out); 
    std::cout << "\n"; 
} 

我得到的輸出是:

0,0,0,0,0,0,0,0,0,0, 
1,2,3,4,5,6,7,8,9,10, 
1,2,3,4,5,6,7,8,9,10, 
1,2,3,4,5,6,7,8,9,10, 
0

我相信問題是你正在傳遞一個指向數組的指針 int * D = new int [100000];

但是,您的函數需要兩個整數數組,它不同於指向數組的指針。

下面是表現摘錄的SSCCE像你想它:

#include <iostream> 
using namespace std; 

void f(int * d, int * a, int length){ 
    for(int k = 0; k < length; k++){ 
      d[k] = a[k]; 
    } 
} 

int main() { 
    int* a = new int[9]; 
    for(int i = 0; i < 9; i++){a[i] = i;} 
    int* d = new int[9]; 
    f(d, a, 9); 

    for(int i = 0; i < 9; i++){ 
      cout << d[i] << " "; 
    } 
}