2017-02-26 53 views
1

其實我打算用戶打印2d數組。然後按行添加數字。 我不知道如何打印行索引號。代碼是:二維陣列錯誤:行索引打印

int arr[3][3]; 
int sum = 0; 

for (int i = 0; i < 3; i++) 
{ 
    for (int j = 0; j < 3; j++) 
     cin >> arr[i][j]; 
} 

cout << endl; 
for (int i = 0; i < 3; i++) 
{ 
    for (int j= 0; j < 3; j++) 
     cout<< arr[i][j]<<" "; 
    cout << endl; 
} 


for (int x = 0; x < 3; x++) 
{ 
    for (int y = 0; y < 3; y++) 

     sum += arr[x][y]; 
    cout << "Row: " << arr[x] << "addition is:" << sum << endl; 
    sum = 0; 
} 

在第二行最後一行arr [x]打印地址。 如果我使用arr [x] [y]它告訴('y'是未定義的)。爲什麼'y'是未定義的? 和善地有人告訴我如何添加數字對角線...?

回答

2

那麼arr[x]是一個數組,其衰減爲指向其第一個元素的指針。所以當您打印arr[x]時,您實際上正在打印&arr[x][0]

我假設你只想打印x

cout << "Row: " << x << ... 
0

我建議你總是在循環使用的支架。這

for (int y = 0; y < 3; y++) 
    sum += arr[x][y]; 
cout << "Row: " << arr[x] << "addition is:" << sum << endl; 

相當於

for (int y = 0; y < 3; y++) { 
    sum += arr[x][y]; 
} 
cout << "Row: " << arr[x] << "addition is:" << sum << endl; 

和循環y外未聲明。你可能想

for (int y = 0; y < 3; y++) { 
    sum += arr[x][y]; 
    cout << "Row: " << arr[x] << "addition is:" << sum << endl; 
} 

而且,你說你要打印的行索引,要麼是xy,但不arr[x][y]這是在指數[x][y]的元素。

1

'y'未定義,因爲它超出了範圍。

斜着添加數字,你可以這樣做:

sum = 0; 
for (int i = 0; i < 3; ++i) 
    sum += arr[i][i];