EmbDev.net

Forum: ARM programming with GCC/GNU tools Accessing consecutively named arrays in C


von asker (Guest)


Rate this post
0 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.

von Mark B. (markbrandis)


Rate this post
0 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
}

von asker (Guest)


Rate this post
0 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.

von gcc-help@gcc.gnu.org (Guest)


Rate this post
0 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
}

von asker (Guest)


Rate this post
0 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

Entering an e-mail address is optional. If you want to receive reply notifications by e-mail, please log in.

Rules — please read before posting

  • Post long source code as attachment, not in the text
  • Posting advertisements is forbidden.

Formatting options

  • [c]C code[/c]
  • [code]code in other languages, ASCII drawings[/code]
  • [math]formula (LaTeX syntax)[/math]




Bild automatisch verkleinern, falls nötig
Note: the original post is older than 6 months. Please don't ask any new questions in this thread, but start a new one.