James Cook
James Cook

Reputation: 13

Creating N identical arrays in C

So, I'm trying to create n identical arrays of the same size but with a slightly different name.

I cannot just define them individually as n depends on an input. The only way I could think to do this is using a for loop, as shown below:

i=0;
for (j=0;j<n;j++){
   int array_i[256];
   i=i+1;
}

I was wondering if there's a way of allowing i to update name of array_i? Or if there is just a better method to do this?

Thanks for any help

Upvotes: 1

Views: 110

Answers (3)

Bregalad
Bregalad

Reputation: 634

You need to declare a dynamic array to static arrays of size 256. Since you don't know in advance how many arrays there is you'll have to allocate them dynamically. Here is how you could do it.

int (*arrays)[256];
unsigned int i;

/* Reserve space for n arrays of 256 int elements */
arrays = malloc(sizeof(int) * 256 * n);  /* or calloc() if you want it zeroed out */

/* Now you can access your arrays as if it was a normal 2D array */
arrays[i][j] = 42;

If and only if you can afford to use C99 variable lengths array, this is also possible :

 int arrays[n][256];

Keep in mind that it will eat n * 256 * sizeof(int) bytes on the stack, so unless you can guarantee that n is a very small number (like 2 or 3) it is probably a bad idea to reserve that much space on the stack, doing it with malloc is cleaner/safer.

Upvotes: 0

haccks
haccks

Reputation: 106092

You can use ## operator which can paste two tokens together to form a single token, but not a good choice.

#define MAKE_ARR(n) array_##n  
int MAKE_ARR(1)[256], MAKE_ARR(2)[256];  

After preprocessing:

 int array_1[256], array_2[256]; 

Upvotes: 0

Lolota F
Lolota F

Reputation: 26

The way I would do it is by using a 2-dimensional array.

How to work with it:

int i, j; //counters
int array[n][256];

for (i=0; i<n; i++) {
    for (j=0; j<256; j++) {
        //enter code for element array[i][j] here
    }
}

Upvotes: 1

Related Questions