2016-10-24 19 views
0

我想知道是否有人可以幫助我製作下面的C程序。代碼只是創建一個指針,然後指定一個整數數組的地址。從那裏,指針被賦予一個值,然後遞增。 輸出顯示數組名稱,數組地址和數組值。輸出按預期工作,除了數組中的最後一項增加了5個而不是一個。帶有指針增量的C程序錯誤值

的代碼如下所示:

#include <stdio.h> 

main() 
{ 
    int numar[4];  //integer array 
    int x;    //value for loop 
    int *p;    //pointer 
    p=numar;   //'point' p to address of numar array (no & necessary as arrays are pointers) 
    for(x=0;x<5;x++) //loop 0-4 
    { 
     *p=x;   //assign the value of the first item in array to x 
     p++;   //increment pointer for next iteration 
    } 
    for(x=0;x<5;x++) //loop 0-4 
    { 
     //display output of array name, array location and array value 
     printf("array[%d] is at address %p with value %d\n", x,&numar[x],numar[x]); 
    } 
    return 0; 
} 

上述代碼的輸出如下所示:

array[0] is at address 0061FF18 with value 0 
array[1] is at address 0061FF1C with value 1 
array[2] is at address 0061FF20 with value 2 
array[3] is at address 0061FF24 with value 3 
array[4] is at address 0061FF28 with value 8 

正如你可以看到,對於陣列所需的值[4]應該是4 ,但它是8.

任何幫助將不勝感激。

非常感謝,

+10

'int numar [4]; '但是看起來像訪問索引4(最大有效值是3),因此您運行數組的末尾並調用未定義的行爲。這裏來的鼻子惡魔.... – John3136

+1

'[4]''意味着陣列有4個元素 –

+0

陣列是***不是***指針。一個評估爲數組的「(子)」表達式將「衰減」爲指向該數組的第一個元素的指針(因此您的賦值工作),但這完全是另一回事。 –

回答

2

爲了使你的代碼編譯,我不得不做出一個變化:我加了「詮釋」前「主」,使主要功能能夠正確返回0

問題是你已經創建了一個大小爲4的整數數組,但你希望它包含5個項目。

int numar[4]; 

意味着你的陣列爲4個元素定義:

numar[0] 
numar[1] 
numar[2] 
numar[3] 

因此,

numar[4] 

是未定義的。

要解決這個問題,讓您的數組一個大小:

int numar[5]; 

我得到的輸出是:

array[0] is at address 0x7fff557f0730 with value 0 
array[1] is at address 0x7fff557f0734 with value 1 
array[2] is at address 0x7fff557f0738 with value 2 
array[3] is at address 0x7fff557f073c with value 3 
array[4] is at address 0x7fff557f0740 with value 4 
+0

非常感謝您的回答。代表我的愚蠢錯誤。 – chrismason954

1

有一個與你正在使用你的數組的索引的問題。

您正在創建一個帶有int numar[4]的4元素陣列。這將創建具有有效索引0,1,2和3的數組。這裏沒有索引[4]

因此,當你在以後灌裝和訪問在for循環數組,你應該設置它們是這樣的:

for(x = 0; x < 4; x++) { 

x < **4**,不5。此循環將檢查索引0,1,2和3.

循環訪問元素[4],該元素不屬於該數組。

2

對不起,沒有辦法讓數組的索引從1開始,所以它們從0開始,所以如果你有一個4個元素的數組,那麼最後一個元素是索引3而不是4的元素。

在您的代碼中,您正在閱讀五個元素,其中只有4個元素的數組。

for(x = 0; x < 5; x++) // iterating five times not 4: 0, 1, 2, 3, 4 
    //.... 

*寫入到陣列的非元件最糟糕的是到加密狗上其它變量,例如:

int a = 0; // initialized to avoid compiler complaining later on 
int numar[4] = {0, 1, 2, 3}; // ok 
numar[4] = 77; // writing to the fifth element which doesn't belong to numar. as you can see variable a right before numar 

cout << a << endl; // a: 77!! where did a get this value? because a is right before numar so element five which doesn't belong to numar was allocated to a 

在這個例子中,我們對其它變量的(a)ABD最無意中dongled令人沮喪的事情是,編譯器不抱怨(我們初始化爲0) 結果是一個容易出錯,這是一個巨大的代碼看起來不可能捕獲。