2017-02-24 42 views
-1

我有一個2維的數組,並且當我第一次打印數組的數據時,日期打印正確,但其他時間的數組[數組] [數據]來自i = 0到最後 - 1.內存的值更改未經許可

顯然是一個邏輯錯誤,但我不明白原因,因爲我複製並粘貼for語句。那麼...... C改變數據?

我使用gcc -std=c99但在此之前,我嘗試使用C++和cout語句。

This is the output screenshot

#include <stdio.h> 

int main(int argc, char *argv[]) 
{ 
    unsigned int numero_jugaderes = 11; 
    unsigned int numero = numero_jugaderes - 1; 

    unsigned int p_a[numero]; 

    float p_aya[numero][numero]; 

    for (unsigned int i = 0; i <= numero; i++) { 
    p_a[i] = i; 
    } 

    for (unsigned int i = 0; i <= numero; i++) { 
    for (unsigned int j = 0; j <= numero; j++) { 
     p_aya[i][j] = (float) (p_a[i] * p_a[j])/100; 
     printf("%f\t", p_aya[i][j]); 
    } 
    puts(""); 
    } 

    puts("\n"); 

    for (unsigned int i = 0; i <= numero; i++) { 
    for (unsigned int j = 0; j <= numero; j++) { 
     printf("%f\t", p_aya[i][j]); 
    } 
    puts(""); 
    } 

    return 0; 
} 
+0

即在技術上是不是一個有效的C++程序,由於C++沒有[可變長度數組(https://en.wikipedia.org/wiki/Variable-length_array)。 –

+0

@user我想這是相反的 –

+0

至於你的問題,請記住,X元素的數組,具有有效的索引範圍'0'到'X - 1'(含)。現在仔細看看你的循環。 –

回答

5

的問題,因爲我看到的是,你遍歷一個條件檢查像

for (unsigned int i = 0; i <= numero; i++) 

的定義爲

unsigned int p_a[numero]; 

和數組你要去off-by-one。這實質上是無效的內存訪問,調用undefined behavior

C數組具有基於0的索引,因此,有效的限制將是

for (unsigned int i = 0; i < numero; i++) 
0

如果有一個數組聲明爲具有numero元件然後指數的有效範圍是[0, numero-1]

因此這樣的環這樣

for (unsigned int i = 0; i <= numero; i++) { 
用於訪問數組元素與未定義行爲 numero元件結果

1

長度數字的數組有數字元素。從索引0到數字1。你正在對待他們,就像他們有索引數字。換成i <= numeroi < numero。對所有循環和j使用相同的操作。