EmbDev.net

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


Author: asker (Guest)
Posted on:

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.

Author: Mark Brandis (markbrandis)
Posted on:

Rate this post
0 useful
not useful
You could use a two-dimensional array, like so:

#include <stdio.h>

#define LIST_ELEM_MAX 4
#define NO_OF_LIST    3

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

  for (i=0; i < NO_OF_LIST; i++)
  {
    for (j=0; j < LIST_ELEM_MAX; j++)
    {
      printf("Element %d of list %d: %d\n", j, i, lists[i][j]);
    }
    printf("\n");
  }
  
  return 0;
}


Author: asker (Guest)
Posted on:

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.

Author: gcc-help@gcc.gnu.org (Guest)
Posted on:

Rate this post
0 useful
not useful
You can do it like so:
extern type_t list1[];
extern type_t list2[];
extern type_t list3[];

type_t *lists[] =
{
    list1,
    list2,
    list3
};

extern void do_list (type_t*);

void do_lists (void)
{
    size_t l;
    
    for (l = 0; l < sizeof (lists) / sizeof (*lists); l++)
        do_list (lists[l]);
}

Author: asker (Guest)
Posted on:

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]
  • [avrasm]AVR assembler code[/avrasm]
  • [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.