我想通过引用传递一个数组,其中数据将从预定义的值列表中添加到该函数中。指针不明确
#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;
}
然而,当我运行此代码,我得到填充了第一人称和第一年龄的阵列。
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);
。当然,我也修改了方法中的代码,但那不是重点。然而,编译成功与前一种方法一样,整个阵列中只有一个人和一个年龄段。这一次,不是第一次,而是最后一次!
我对此感到不知所措。我真的认为我对指针的工作原理有了大致的了解,但这只是证明我错了。我真的很感谢在这个问题上的任何帮助。
预先感谢您。
使用'人'++是怎么回事,如果用户想调用'上分配的内存free'是一个问题。使用'people [i] .name'和'people [i] .age'更好。 –
@RSahu是的,但是按照OP使用的惯例移动指针会使代码的其余部分保持不变 – Gopi
是的,我打算添加'free'调用。但是,感谢这个想法。我会记住这一点,以备将来使用 –