[英]C++ pointing a pointer to an array and accessing?
如何訪問指向數組第一個元素的指針的值。 我在下面嘗試過,但是代碼無法構建。
int _tmain(int argc, _TCHAR* argv[])
{
/// pointers array
mint *yellow [5];
/// each pointers array point to an an array of 10 elements
for (int i = 0; i < 5; i++)
{
yellow[i] = new int [10] ;
}
/// assigning to pointer 1, array 1, element 1 the value of 0;
///
*yellow[0][1][0] = 0;
std::cout << *yellow[0][1][0];
system("pause");
return 0;
}
更新-
盡管我沒有元素20,但是我仍然能夠分配和打印元素20
int _tmain(int argc, _TCHAR* argv[])
{
/// pointers array
int *yellow [5];
/// each pointers array to an an array of 10 elements
for (int i = 0; i < 5; i++)
{
yellow[i] = new int [10] ;
}
/// assigning to pointer 1, array 1, element 1 the value of 0;
///
yellow[0][20] = 0;
std::cout << yellow[0][20];
system("pause");
return 0;
要訪問第一個數組的第一個元素,請使用
yellow[0][0] = 0;
要么
(*yellow)[0] = 0;
要訪問第二個數組的第三個元素,請使用
yellow[1][2] = 0;
要么
(*(yellow+1))[2] = 0;
概括一下這個想法...要訪問第M個數組的第N個元素,請使用
yellow[M-1][N-1] = 0;
要么
(*(yellow+M-1))[N-1] = 0;
實際上,通過將其分配給yellow [0] [20]可以調用未定義的行為 。 換句話說,您的程序並不總是保證輸出0,該值存儲在yellow [0] [20]中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.