Two dimensional array with char pointer in c

1080 views c

In the following code I am trying for each band to get the number of band members. I've tried a number of things but nothing works. The following looks like it should but doesn't.

If any one could point out what I'm doing wrong it would be greatly appreciated.

numMembers = sizeof(bands[0]) / sizeof(bands[0].members);

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    int         i;  
    int         j;  
    int         numBands;
    int         numMembers;
    int         limit = 4;

    struct band {
        char        name[10];
        char        *members[20];

    const struct band bands[] =
        {   {"Beatles", {"John", "George", "Paul", "Ringo", "Pete", "George"} },
            {"Stones",  {"Mick", "Keith", "Bill", "Charlie", "Brian"} },
            {"Who",     {"Pete", "Roger", "Keith", "John"} },
            {"JHE",     {"Jimmy", "Noel", "Mitch"} }  };  

    numBands   = sizeof(bands) / sizeof(bands[0]);

    for ( i = 0; i < numBands; ++i ) { 
        printf ("%s\n", bands[i].name);
        numMembers = sizeof(bands[0]) / sizeof(bands[0].members);
        for ( j = 0; j < numMembers; ++j )
            printf ("\t%s", bands[i].members[j]);
        printf ("\n");

    return 0;

answered question

printf ("\t%s", bands[i].members[j]); not valid when bands[i].members[j] is NULL.

1 Answer


For numMembers = sizeof(bands[0]) / sizeof(bands[0].members);

sizeofband(bands[0]) will give the size of one band struct - that is the 10 bytes for name, and then 20 * the size of a pointer.

sizeof(bands[0].members); will give 20*thesizeof a pointer

Not what you want.

posted this

Have an answer?


Please login first before posting an answer.