BhishanPoudel
BhishanPoudel

Reputation: 17154

How can we iterate through multiple arrays in C programming?

I have some multidimensional arrays, I have to run them inside a loop. my code looks like this:

int naxes1[3] = { 10,20,1};
int naxes2[3] = { 10,20,1};
int naxes3[3] = { 10,20,1};

I like to have a array like this

int naxes[3] = {naxes1, naxes2, naxes3};

so that I can iterate through them like this:

for ( i=0; i<3; i++)
{
    fits_get_img_size(names[0],  3, naxes[i],  &status);
}

Here, I am using cfitsio library and it takes naxes1,naxes2,naxes3 as three dimensional arrays. In simple words, how can we interate through multiple arrays?

Upvotes: 0

Views: 1374

Answers (2)

pablo1977
pablo1977

Reputation: 4433

It depends of your needs.
As Joachim Pileborg pointed out in his answer, you can use an array of pointers.

On the other hand, you can also define at the beginning of the program a bidimensional array with the values you want:

#define  N  4
int naxes[N][3] = { {10,20,1}, { 10,20,1}, { 10,20,1}, {1, 2, 3} };

printf("naxes[3][2] == %d\n", naxes[3][2]);

Here N denotes the number of arrays having 3 elements.
It can be changed to hold the number of elements you need.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409176

You are very close, but you have to remember that e.g. naxes1 isn't an int, but it can be an int *.

So instead of having an array of int for the collection, you should have an array of pointer to int:

int *naxes[3] = {naxes1, naxes2, naxes3};

This should of course have become very evident if you only tried to compile your program. Next time, please try that, and actually read the error messages you get (they often contain hints about what you should do) before asking a question.

Upvotes: 3

Related Questions