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?

3 Answers 3

6

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}};
Sign up to request clarification or add additional context in comments.

3 Comments

COOKIES! I LOOOOOOOOOVE COOKIES!
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.
I use gcc 4.0. Apparently this is the default setting if you use iPhone OS 2.2.1.
2

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

Comments

0

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.

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.