Say we have this:
int array[2]={1,2};
int *ptr = array;
cout<<ptr[1];
Now if we have this
int array[2][2];
//pretend it contains values, save me writing code:0
how do i assign a pointer to this multi dimensional array?
Thanks
Printable View
Say we have this:
int array[2]={1,2};
int *ptr = array;
cout<<ptr[1];
Now if we have this
int array[2][2];
//pretend it contains values, save me writing code:0
how do i assign a pointer to this multi dimensional array?
Thanks
If you want a pointer to an array of 2 elements:
Code:int (*p)[2] = array;
I want a pointer to the multi dimensional array.
Was thinking i need to use a double pointer for it. But just cant seem to implement it.
Why would you want that? You more likely want either a pointer to an array of 2 elements so that you can iterate over the elements of the 2D array, or a pointer to an int so that you can directly iterate over the ints in the 2D array.Quote:
Originally Posted by newbie30
With a one dimensional array we can have a pointer to it, correct?
but with multidimensional you cant?
I was just playing around with code and i was just trying to print the elements of the multidimensional array using a pointer, the same way you can with a one dimensional array.
Yes, e.g.,Quote:
Originally Posted by newbie30
Code:int numbers[2] = {1, 2};
int (*p)[2] = &numbers;
No, you also can:Quote:
Originally Posted by newbie30
Notice that I am taking you literally here: we are talking about pointer to arrays, not pointers to the first elements of arrays, hence I write &numbers on the right hand side of the assignment rather than just numbers to get the address of the array.Code:int numbers[2][2] = {{1, 2}, {3, 4}};
int (*p)[2][2] = &numbers;
You can try:Quote:
Originally Posted by newbie30
This would be the "pointer to an int so that you can directly iterate over the ints in the 2D array" idea.Code:#include <iostream>
#include <cstddef>
int main()
{
int numbers[2][2] = {{1, 2}, {3, 4}};
const std::size_t total_size = sizeof(numbers) / sizeof(numbers[0][0]);
for (int* p = &numbers[0][0], *end = &numbers[0][0] + total_size; p != end; ++p)
{
std::cout << *p << ' ';
}
std::cout << std::endl;
}
int myArray={{0.1} , {2,3} }
Int (*ptr) [2][2] = &myArray;
int(*ptr)[2][2] = &array;
I know we are pointing to the address of the array but what does the first part actually say:
ie this part int(*ptr)[2][2]
Thanks
That means "a pointer named ptr to an array of two arrays of two ints".Quote:
Originally Posted by newbie30
but why the brackets around the pointer?
Ugly syntax inherited from C :DQuote:
Originally Posted by newbie30
Without the parentheses you end up with an array of 2 arrays of 2 int pointers.
thanks the perfect answer for me.