指针歧义

Pointers Ambiguity

我正在尝试通过引用一个函数来传递数组,在该函数中,数据将从预定义的值列表中添加到数组中。

#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;
}

但是,当我 运行 这段代码时,我得到的数组填充了第 1 个人和第 1 个年龄。

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)

我尝试了一种不同的方法,通过调用 insert(&people, i, names[i], ages[i]); 并将方法签名修改为 void insert(person** next, int position, char* name, int age);。当然,我也修改了方法中的代码,但这不是重点。编译成功了,但是,就像以前的方法一样,我在整个数组中只得到一个人和一个年龄。这次不是第一个,而是最后一个!

我对此一头雾水。我真的以为我对指针的工作原理有一个大致的了解,但这只是证明我错了。如果能就此主题提供任何帮助,我将不胜感激。

提前致谢。

您的打印循环总是将相同的值传递给 printf。你想打印 people[i].namepeople[i].age.

您应该在像 people ++ 一样打印时移动您的指针 people,以便打印所有值。

只需使用

people[i].agepeople[i].name