0

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;
}
1
  • 2
    Welcome to SO. Please provide us with more information what is going wrong for you. Just pasting code is not enough. Commented Oct 26, 2010 at 16:18

3 Answers 3

2

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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].

2 Comments

thanks for your help :) sorry about the bad style this is one of my first c programs
No problem - these are just some suggestions to improve.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.