Accessing consecutively named arrays in C

Guest #2584727
Rate this post
useful
not useful
This may be a long shot, but anyway...

Say I have lots of arrays named list1[], list2[], list3[], etc.

I want a while() loop where I do something like this:

while(1)
{
   afunction(listX);
}


....where X is incremented each time.

In case you wonder why I want to do this, I'm saving C arrays from 
Wireshark to feed into C code for testing and the arrays it generates 
have incrementing numbers.  Typing in all these array names manually is 
tiring.
#2584763
Rate this post
useful
not useful
You could use a two-dimensional array, like so:

1
#include <stdio.h>
2

3
#define LIST_ELEM_MAX 4
4
#define NO_OF_LIST    3
5

6
int main()
7
{
8
  unsigned int i, j;
9
  unsigned int lists[NO_OF_LIST][LIST_ELEM_MAX] = { { 1,  2,  3,  4 },
10
                                                    { 2,  4,  6,  8 },
11
                                                    { 5, 10, 15, 20 } };
12

13
  for (i=0; i < NO_OF_LIST; i++)
14
  {
15
    for (j=0; j < LIST_ELEM_MAX; j++)
16
    {
17
      printf("Element %d of list %d: %d\n", j, i, lists[i][j]);
18
    }
19
    printf("\n");
20
  }
21
  
22
  return 0;
23
}
Guest #2584776
Rate this post
useful
not useful
Thanks for the reply, but that still means I have to change dozens or 
maybe hundreds of arrays that I simply cut and paste out of Wireshark.

If I could put some syntax around the entire block of arrays without 
having to change the syntax of each one, that would be better.
Guest #2585945
Rate this post
useful
not useful
You can do it like so:
1
extern type_t list1[];
2
extern type_t list2[];
3
extern type_t list3[];
4

5
type_t *lists[] =
6
{
7
    list1,
8
    list2,
9
    list3
10
};
11

12
extern void do_list (type_t*);
13

14
void do_lists (void)
15
{
16
    size_t l;
17
    
18
    for (l = 0; l < sizeof (lists) / sizeof (*lists); l++)
19
        do_list (lists[l]);
20
}
Guest #2586239
Rate this post
useful
not useful
I ended up writing a simple C program to generate a very long list of 
function calls with incrementing array names being passed to the 
function.  It's messy, but it's the easiest thing I've come up with.

Reply

Please log in before posting.

or

Log in with Google account

Registration is free and takes only a minute.

Register now