How to initialize a 2D array with pointer.
int *mapTable[] = { {1,10} , {2,20} , {3,30} , {4,40} }; // It's giving error
Here int *mapTable is giving an error.
How can I declare them properly?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
int *mapTable[]is not a 2D array: it is a 1D array of pointers.But then you go and use a 2D array initialiser
{ {1,10} , {2,20} , {3,30} , {4,40} }.That’s why it’s “giving error”.
The 2D array way
Try:
And, yes, you do need to specify the size of that second dimension.
The 1D array of pointers way
This is a little more involved, and is usually too complex to be worth it.
It also usually requires dynamic allocation, causing a total mess with object lifetime:
As you can see, this is not ideal.
You can avoid dynamic allocation:
But I’m not sure why you’d want to go down this avenue.