0

In C++, We can do the following:

#include <iostream>

int main() 
{  
    int arr[] = {1,2,3};
    int *p = arr;
    return 0;
}

However this dosen't seem to work:

#include <iostream>

int main() 
{  
    int arr[][3] = {{1,2,3},{4,5,6}};
    int **p = arr;
    return 0;
}

Can somebody please explain me why it does not work for 2d arrays.

Also when dealing with pointers and 2d arrays, consider the following code:

#include <iostream>

int N = 5;
void func(int arr[][N]){

    return;
}


int main() 
{  
   int arr[N][N];
   return 0;
} 

The above code doesn't work either and i don't know why? Error: expression must have a constant value (Variable N)

Kakarot_7
  • 302
  • 1
  • 5
  • 14
  • 1
    please include the compiler errors in the question. "Doesn't work" can mean anything – 463035818_is_not_an_ai Oct 28 '20 at 10:23
  • 1
    and please focus on one questions per question. Array sizes must be compile time constants, hence `int N = 5;` cannot be used as array size, that has nothing to do with 2d or passing the array to a function – 463035818_is_not_an_ai Oct 28 '20 at 10:26
  • 1
    Consider using [Boost](https://boost.org/) or at least [standard C++ containers](https://en.cppreference.com/w/cpp/container). Read the documentation of your C++ compiler (perhaps [GCC](http://gcc.gnu.org/)...) and debugger (maybe [GDB](https://www.gnu.org/software/gdb/)...). With GCC, compile your code with `g++ -Wall -Wextra -g` – Basile Starynkevitch Oct 28 '20 at 10:26
  • 2
    Array to pointer decay is a good way to get headaches, especially since things `void func(int arr[][N]){` _look_ like they were taking arrays as parameters. Consider using [`std::array`](https://en.cppreference.com/w/cpp/container/array) instead. – Lukas-T Oct 28 '20 at 10:28

0 Answers0