Accessing consecutively named arrays in C

Guest #2584727
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.
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
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
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
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

A question of your own? This thread is over 14 years old. Ask it in a thread of its own – more people read along there, and it gets answered more often and sooner.

Start a new thread

A fix, an addition or feedback on this thread? Then reply here.

Formatting
  • [c]C-Code[/c]
  • [code]code in other languages, ASCII drawings[/code]
  • [math]formula (LaTeX syntax)[/math]
  • [[Title]] – link to an article
  • Link to another post: right-click its post ID (#8078628), copy the address, paste it into the text

More about formatting

Post long source code as an attachment, not in the text.

Already registered? Log in

Not shown to anyone. We send you a link; your post appears once you confirm it there.

By submitting you create a free account and accept the terms of use.