最近,我調試了一個程序,發現我經常犯的一個錯誤,但是在編譯期間它沒有顯示爲警告,所以我只是假設一切都是到位,並確定。我有點糊塗剛剛發生在下面的代碼:將數組的地址作爲函數參數
void foo(char b[2]);
char a[2] = {1, 2};
foo(a); // I always assumed that this would pass the entire array to be
// duplicate in stack, guess I was wrong all this while
// Instead the address of the array was passed
void foo(char b[2])
{
// Value of b[0], b[1]?
// Does this mean : 1) b[0] == &a[0]?
// or 2) b[0] == &a[0+2]?
// Compiler didn't complain, so I assume this is a valid syntax
}
foo的(焦B [2]),這是否意味着我會限制訪問大小爲2,例如b [0],b [1]有效,但不是b [2]等等? – freonix
不,您放入括號中的實際值沒有相關性。 – lccarrasco
更清楚的是,你可以用任意大小的字符組調用'f',在'f'裏面你可以訪問數組中所有有效的位置而沒有問題,但是如果你嘗試訪問超出實際大小的位置你的數組屬於你未定義的行爲,這意味着任何事情都可能發生。 – lccarrasco