user3599681
user3599681

Reputation:

Pointers Ambiguity

I am trying to pass an array by reference to a function where data would get added to it from a predefined list of values.

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

#define ARR_SIZE 7

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

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

static void insert(person*, char*, int);

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

  person* people = (person*) malloc(ARR_SIZE * sizeof(person));

  for (int i = 0; i < ARR_SIZE; ++i) {
    insert(&people[i], names[i], ages[i]);
  }

  for (int i = 0; i < ARR_SIZE; ++i) {
    printf("Person #%d: (Name: %s; Age: %d)\n", i + 1, people->name, people->age);
  }

  return 0;
}

static void insert(person* next, char* name, int age) {
  next->name = name;
  next->age = age;
}

However, when I run this code, I get the array populated with the 1st person and 1st age.

Person #1: (Name: Simon; Age: 22)
Person #2: (Name: Simon; Age: 22)
Person #3: (Name: Simon; Age: 22)
Person #4: (Name: Simon; Age: 22)
Person #5: (Name: Simon; Age: 22)
Person #6: (Name: Simon; Age: 22)
Person #7: (Name: Simon; Age: 22)

I have tried a different approach, by calling insert(&people, i, names[i], ages[i]); and modified the method signature to void insert(person** next, int position, char* name, int age);. Of course, I modified the code in the method too, but that's not the point. Compilation was successful, however, just like with the previous approach, I was getting only one person and one age in the whole array. This time, not the first one, but the last one!

I am at a loss with this. I really thought I had a general understanding over how pointers work, but this just comes to prove me wrong. I would really appreciate any kind of help on this subject.

Thank you in advance.

Upvotes: 0

Views: 78

Answers (2)

Gopi
Gopi

Reputation: 19874

You should be moving your pointer people while printing like people ++ in-order to print all the values.

or

Just use

people[i].age and people[i].name

Upvotes: 1

Jens Gustedt
Jens Gustedt

Reputation: 78963

Your loop for printing always passes the same value to printf. You want to print people[i].name and people[i].age.

Upvotes: 3

Related Questions