0

Dear all,

In the function below,

how should the array of arrays data structure be defined and used?

void foo(int option)
{
    int i =0;
    char Colstr[3][15] = {"Red","Blue","Green"};
    char Volstr[7][15] = {"1","2","3","3.5","4","4.5","5"};
    char Sndstr[4][15] =  {"lo","med","hi","vhi"};
    int numSTrings[2] = {3,7,4};

    char *arrayOfarrays[] = {Colstr,Volstr,Sndstr}; // How should this be declared?

      for(i=0;i<numSTrings[option];i++)
            printf("%s\n", ????);                   // How should arrayOfarrays be referred?
}

thanks,
shri

3
Contributors
3
Replies
15
Views
4 Years
Discussion Span
Last Post by cshrikanth
0

Directly you'd do it like this:

#include <stdio.h>

#define length(a) (sizeof (a) / sizeof *(a))

int main(void)
{
    char Colstr[3][15] = {"Red", "Blue", "Green"};
    char Volstr[7][15] = {"1", "2", "3", "3.5", "4", "4.5", "5"};
    char Sndstr[4][15] = {"lo", "med", "hi", "vhi"};
    int n[3] = {3, 7, 4};
    int i, j;

    char (*a[])[15] = {Colstr, Volstr, Sndstr};

    for (i = 0; i < length(a); i++) {
        for (j = 0; j < n[i]; j++) {
            printf("'%s'\t", a[i][j]);
        }

        putchar('\n');
    }

    return 0;
}

But that's awkward. I'd recommend using a typedef for your string instead:

#include <stdio.h>

#define length(a) (sizeof (a) / sizeof *(a))

typedef char char15[15];

int main(void)
{
    char15 Colstr[3] = {"Red", "Blue", "Green"};
    char15 Volstr[7] = {"1", "2", "3", "3.5", "4", "4.5", "5"};
    char15 Sndstr[4] = {"lo", "med", "hi", "vhi"};
    int n[3] = {3, 7, 4};
    int i, j;

    char15 *a[] = {Colstr, Volstr, Sndstr};

    for (i = 0; i < length(a); i++) {
        for (j = 0; j < n[i]; j++) {
            printf("'%s'\t", a[i][j]);
        }

        putchar('\n');
    }

    return 0;
}

This greatly simplifies the syntax and also more clearly shows your intentions. It's also easier to understand for folks who aren't intimately familiar with the dark corners of C's declaration syntax.

0

One way is like this

void foo(int option)
{
    int i =0;
    char *Colstr[] = {"Red","Blue","Green"};
    char *Volstr[] = {"1","2","3","3.5","4","4.5","5"};
    char *Sndstr[] =  {"lo","med","hi","vhi"};
    int numSTrings[] = {3,7,4};

    char **arrayOfarrays[] = {Colstr,Volstr,Sndstr}; // How should this be declared?

      for(i=0;i<numSTrings[option];i++)
            printf("%s\n", ????);                   // How should arrayOfarrays be referred?
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.