Reputation: 77
how do I access the value of a pointer to an array first element. I have attempted below but code won't build.
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;
}
Update-
although that I don't have an element 20 but I am still able to assign and print the element 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;
Upvotes: 0
Views: 52
Reputation: 81
Actually, by assigning to yellow[0][20] you are invoking undefined behavior. In other words, your program isn't always gauranteed to print 0, the value stored at yellow[0][20].
Upvotes: 0
Reputation: 206557
To access the first element of the first array, use
yellow[0][0] = 0;
or
(*yellow)[0] = 0;
To access the third element of the second array, use
yellow[1][2] = 0;
or
(*(yellow+1))[2] = 0;
To generalize the idea... To access the N-th element of the M-th array, use
yellow[M-1][N-1] = 0;
or
(*(yellow+M-1))[N-1] = 0;
Upvotes: 1