views:

101

answers:

3

I want to have a static array with arrays in it. I know you can make a normal array like this:

int test[] = {1,2,3,4};

But I want to do something like this (Xcode gives me a bunch of warnings and stuff):

int test[] = {{1,2}, {3,4}};

In python it would be:

arr = [[1,2], [3,4]];

What's the proper way to do this?

A: 

You need array of arrays or 2 dimensional arrays :

int test[][] = {{1,2}, {3,4}};

EDIT : I am out of touch with C. This is almost correct but not entirely as shown by LiraNuna.

fastcodejava
+6  A: 

To have a multidimensional array, you'd need two levels of arrays:

int test[][] = {{1,2}, {3,4}};

However, that will not work, as you need to declare the size of the inner-most arrays except the last one:

int test[2][] = {{1,2}, {3,4}};

Or if you need an even stricter type safety:

int test[2][2] = {{1,2}, {3,4}};
LiraNuna
Thanks! Cookies for you.
quano
COOKIES! I LOOOOOOOOOVE COOKIES!
LiraNuna
I think it's the other way around actually, i.e. [][2]. It wouldn't compile for me at least unless I did it that way.
quano
What GCC version are you using? This works on GCC 4.4.1.
LiraNuna
I use gcc 4.0. Apparently this is the default setting if you use iPhone OS 2.2.1.
quano
+2  A: 

You can use typedef like this

typedef int data[2];
data arr[] = {{1,2},{3,4}};

This approach may be clearer if you use a "good" name for the type definition

GuidoMB