C 打印结构数组

C 打印结构数组,c,arrays,struct,C,Arrays,Struct,如果看不到程序的其余部分,就不可能有效地回答这个问题。但是,您提到“跑步时撞车”,这通常意味着: 您违反了某个函数的API,向其传递了错误类型的参数或错误数量的参数 您正试图通过指向不存在内存的指针取消引用或赋值 我强烈建议您尝试以下方法: 首先,使用-Wall-Werror编译您的程序(假定这是gcc),并注意您得到的所有错误消息,并修复所有错误消息 其次,尝试检查使用gdb获得的核心转储的堆栈跟踪——这将准确地告诉您程序崩溃的位置,至少如果您使用-g编译的话 第三,尝试使用Valgri

如果看不到程序的其余部分,就不可能有效地回答这个问题。但是,您提到“跑步时撞车”,这通常意味着:

  • 您违反了某个函数的API,向其传递了错误类型的参数或错误数量的参数
  • 您正试图通过指向不存在内存的指针取消引用或赋值
我强烈建议您尝试以下方法:

  • 首先,使用-Wall-Werror编译您的程序(假定这是gcc),并注意您得到的所有错误消息,并修复所有错误消息
  • 其次,尝试检查使用gdb获得的核心转储的堆栈跟踪——这将准确地告诉您程序崩溃的位置,至少如果您使用-g编译的话
  • 第三,尝试使用Valgrind这样的系统运行,该系统旨在查找和诊断内存错误

循环似乎构造正确。这表明问题要么在于数据的构造方式,要么在于发送到此函数的参数存在问题。

您应该将函数编写为

无效打印(部分项目[],内部项目计数){ ... ... }


在函数调用中:print(item,f)

item
,作为添加的参数是该函数的本地参数。因此,当您修改它时,这不会影响传递给它的变量。为了将修改后的
指针返回,您需要传递一个指向它的指针(指向指针的指针):

然后使用
*项目
(或
(*项目)
)当前在
添加中使用
项目
的任何地方

void add(part **item, int *part_count)

结果就是这样。不确定是否需要使用
**struct
,但这是我唯一可以使用的方法。

这部分是正确的。。您可以发布填充项数组的代码吗?如果让我猜的话,我会说,
item[I].name
不是以null结尾的……它到底是如何崩溃的?编译时有警告吗?代码片段看起来不错。请显示调用您的
打印
的代码,并设置您打印的数组。如果这是家庭作业,您应该使用标记“家庭作业”…我敢打赌,您使用不正确的
part\u count
参数来调用它。可能是一个
sizeof
而不是数组中的结构数?为什么将*更改为[]?实际上,使用
[]
会让新程序员误以为它是一个数组,而它是一个指针。
void add(part *item, int *part_count)
 {
      if (!item)
      {
         item = malloc(sizeof(part));
      }

      item = realloc(item, sizeof(part) * *part_count + 1);

      item[*part_count].name = malloc(sizeof(char)*64); // max of 64 characters

      printf("Please enter item name: ");
      scanf("%65s", item[*part_count].name);

      printf("Please enter item price: ");
      scanf("%f", &item[*part_count].price);

      printf("Please enter item quantity: ");
      scanf("%d", &item[*part_count].quantity);

      *part_count = *part_count+ 1;
 }
void add(part **item, int *part_count)
void add(part **item, int *part_count)
{
  char temp[100];

  if (!(*item)){
   //printf("first alloc\n");
       *item = malloc(sizeof(part)*3);
  }
  else if (*part_count>= 3){
  //printf("realloc\n");
      *item = realloc(*item, sizeof(part) * (*part_count + 1));
  }

  item[0][*part_count].name = malloc(sizeof(char)*100); // max of 100 characters

  printf("Please enter item name: \n");
  fgets(temp, 100, stdin);     
  strcpy(item[0][*part_count].name, temp);      


  printf("Please enter item price: \n");
  fgets(temp, 100, stdin);
  sscanf(temp, "%f", &item[0][*part_count].price);      


  printf("Please enter item quantity: \n");
  fgets(temp, 100, stdin);
  sscanf(temp, "%d", &item[0][*part_count].quantity);   


  *part_count = *part_count+ 1;
}