c - 帮助使用 c 中的指针、结构体和数组

标签 c struct

需要帮助打印结构体指针数组 我哪里出错了?请帮忙

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

最佳答案

在进行 malloc 时,您将 structperson 声明为值而不是指针。然后您尝试从那时起将其作为指针引用(即用星号取消引用它)。

Here is how I would write it 。我做了一些更改,例如删除静态变量(您应该处理分配它的数组,您的函数不应该存储数组的状态,然后没有其他人可以使用它)。

关于c - 帮助使用 c 中的指针、结构体和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4025627/

相关文章:

c - 如何为您的程序分配更多内存(GCC)

c - Makefile 在 ubuntu 14.04 上失败 - undefined reference

c - 两个空格作为 scanf 分隔符

c - 实际输出是什么,为什么?

c - 如果没有括号,如何处理 if 和 else?

c - 声明链表节点

c++ - 在 C++ 中返回结构

c++ - struct c++ 中的默认参数

arrays - 如何使用 swift 将自定义结构数组保存到 NSUserDefault?

c - 来自 valgrind 的未初始化值