What’s the difference between declaring multidimensional arrays like this:
int a[5][5];
or this
int* a[5];
?
Which one is better to use? Thanks.
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.
Both may be used to declare 2-dimensional arrays.
In the first case, 25 int elements are allocated in a contiguous region in memory.
In this case the expression
a[i][j]is translated by the compiler to*(a + i*5 + j).The second one allocates 5 pointers to
int. You can make it work as a two dimensional array by allocating vectors ofintand making these pointers point to these vectors.In this case
a[i][j]means get the pointer thata[i]points to, then look up the 5th element in that vector. I.e.a[i][j]is translated to*(a[i] + j).Note that in the second case, rows need not be of the same length.