tags:

views:

67

answers:

3

help needed printing array of pointers to structs where am i going wrong ? please help

include <stdio.h>
include <stdlib.h>


define HOW_MANY 7

char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
        "Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};


struct person
{
  char *name;
  int age;
};


static void insert (struct person *people[], char *name, int age) {
  static int nextfreeplace = 0;


  typedef struct person newperson;
   newperson *structperson = (newperson*)malloc(sizeof(newperson));
   (*structperson).name= name;
   (*structperson).age = age;
   printf("%s",(*structperson).name);

   people[nextfreeplace] = &structperson;
   printf("%s",(*people[nextfreeplace]).name);

  nextfreeplace++;
}

int main(int argc, char **argv) {


  struct person *people[HOW_MANY];

  for (int c=0; c < HOW_MANY;c++) {
    insert (people, names[c], ages[c]);
  }

   print the people array here
  for (int i=0; i < HOW_MANY;i++) {
    printf("%s \n",&(*people[i]).name);
  }
  return 0;
}
A: 

i want to add the data to structs which are person and then make an array of pointers to the person and then print them out. currently i am getting output which is not readable e.g 11112012.

learner123
A: 

Lots of style problems:

  • Don't cast the return value of malloc.
  • Instead of passing sizeof(newperson) to malloc, use sizeof *structperson.
  • Use the -> operator, i.e. structperson->name instead of (*structperson).name.
  • Clean up the (confusing a misleading) names you've used for your typedef and variables.
  • In place of HOW_MANY, you might use sizeof names/sizeof names[0].
R..
thanks for your help :) sorry about the bad style this is one of my first c programs
learner123
No problem - these are just some suggestions to improve.
R..
+1  A: 

Where you malloc, you are declaring your structperson as a value instead of a pointer. Then you try to refer to it from then on as a pointer (ie dereferencing it with the asterisk).

Here is how I would write it. I make a number of changes, such as remove the static var (you should handle the array where your are assigning it, your function shouldn't be storing the state of the array, then no one else can ever use it).

Joshua Cheek