0

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;
1
  • 1
    You're only created 2 dimensions, so why are you using indexing for 3 dimensions? yellow[0][1] = 0; should work. Commented Feb 25, 2015 at 18:49

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks- I have tried what you have stated, and now it caused another questions. I have updated the post.
@someGuy, What you have added is syntactically correct but it will create problems at run time since you are accessing the arrays out of bounds. Accessing arrays out of bounds is undefined behavior. It might seem to work but it will fail at the most inopportune moment.
0

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].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.