0

I am trying to understand how to use pointers with multidimensional arrays (E.g: 2 dimensions, 3 dimensions...). I saw a lot of resources online for it, but I still can't seem to understand it. The syntax is also throwing me off. What do these following syntaxes mean (Why do we need parenthesis)? What does the code do and how does it work? Thank you!

Example 1

int (*array)[5] = new int[10][5];

Example 2

int c[3][2][2]; 
int (*p)[2][2] = c; 
3
  • 5
    int *array[5]; defines array as an array of five pointers to int. int (*array)[5]; defines array as a pointer to an array of five int values. Commented Jul 14, 2020 at 13:50
  • @Someprogrammerdude is right and very succinct. You can read more on this here. Commented Jul 14, 2020 at 13:53
  • 2
    This toy tool can be of help to fiddle for distinct meanings of types with and without parentheses: C gibberish ↔ English Commented Jul 14, 2020 at 13:59

1 Answer 1

3
  1. int (*arr)[5] : arr is pointer, pointing to an array of 5 ints
  2. int (*p)[2][2] = c; : p is a pointer, pointing to an array of 2, with each row having an array of 2 ints

How does it work? Look at the following simple example:

    int (*array)[2] = new int[3][2];

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 2; j++)
            array[i][j] = i + j;
    }
    
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 2; j++)
            cout << array[i][j] << ' ';
        cout << '\n';
    }

Output:

0 1 
1 2 
2 3 

Why do we need parenthesis?

Consider:

int *arr[3];

Here, arr is an array of size 3, which can store 3 pointers. So it is an array of pointers. See:

int a = 10;
int b = 20;
int c = 30;
arr[0] = &a; //arr[0] pointing to a
arr[1] = &b; //arr[1] pointing to b
arr[2] = &c; //arr[2] pointing to c
Sign up to request clarification or add additional context in comments.

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.