假設您有一個int arr [],其中包含10個元素和一個int * ptr。 我認爲以下幾行會導致一個錯誤,但它會打印0作爲存儲在ptr中的值。它是如何計算爲0的?指向數組中的第11個元素,其中有10個元素C
ptr = arr;//ptr currently points to the first element in arr
ptr = (arr + 10);//points to what would be the llth element in memory for arr
printf("ptr %p\n", ptr);//this displays where the 11th element would be in memory
printf("*ptr %i\n", *ptr);//why would this print 0?
它是否使用指針算術來解決這個問題呢,還是其他的東西? –
它使用指針算術來獲取地址,並指向結尾的元素是合法的。但是一旦你試圖解引用它,你就會處於未定義的行爲狀態。 –