Jasmine
Jasmine

Reputation: 323

Array of structures: printing all members of each structure

I'm trying to print out all the members of each structure from a list. I was provided the print functions below to print out an element from a generic list.

Here is the structure definition of my list, which is in a generic list ADT c file:

struct list_type {
  void *data;
  int size;
  int capacity;
  int elementSize;
  int (*comparePtr) (void *d1, void *d2);
};

So in a generic list ADT c file, I have this print function:

// client needs to send a pointer to a function capable of printing an element
void printl(ListType listptr, void (*printItem) (void *d)) {
  int i;
  for(i = 0; i < listptr->size; i++) {
    // since we cannot use data[i], we need to calculate the address
    // of the element to be sent to the client's print function
    // since data is of type void, the formula is:
    // the beginning address of the array + (offset x element size)
    printItem(listptr->data + i * (listptr->elementSize) );
    printf(" ");
  }
  printf("\n");
}

I call my printl function like so:

printl(clientList, printItem);

In my driver file, there's a function to print out an element from the list:

void printItem (int* p) {
    printf("%d", *p);
    //`my attempt at printing the members of an individual structure from the list
    // printf("%s", ((Client *)&p)[0]); 
}

Here is my Client structure definition:

struct client_tag {
    char id[5];
    char name[30];
    char email[30];
    char phoneNum[15];
};

When I run the program, I get a bunch of weird characters. How do I fix this?

Upvotes: 1

Views: 1093

Answers (1)

Mark Lakata
Mark Lakata

Reputation: 20828

Assuming you left out the line

typedef struct client_tag Client;

and assuming the strings of Client are guaranteed to be null terminated, this is the idea:

void printItem (const Client* p) {
    printf("%s\n", p->id);
}

Upvotes: 1

Related Questions