繁体   English   中英

C 程序 - 跳过用户输入

[英]C program - skipping user input

我创建了一个程序,它使用数组和数组指针来存储用户的动物名称、动物类别和年龄。 但是我运行的时候,输入名字age和category后出现分段错误 我想知道是否有人可以指导我如何修复它,我对 C 编程非常陌生。

这是我应该完成的任务:

编写一个程序,定义一个动物数据类型,带有动物名称、年龄和类别(猫、狗等),以及一个存储动物指针数组的动物数组类型。 您的程序将提示用户输入任意数量的动物的数据。 它将为每个动物初始化一个动态分配的动物结构,并将每个动物存储在动物数组结构的实例中。 然后,您的程序会将所有动物信息打印到屏幕上。 您将把 C 程序作为一个文件上传。

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

typedef struct {
char *name;
char *category;
int age;
} AnimalType;

typedef struct {
AnimalType basicInfo;
AnimalType *arr[];
} AnimalArrayType;

void initAnimal(char *n, char *c, int a, AnimalArrayType *ar);
void printAnimal(const AnimalArrayType *stuPtr);

int main() {    

  AnimalArrayType *array;
  int numAn;
  char name[20];
  char category[20];
  int  age;

  printf("Please enter the number of animals you want to input: ");
  scanf("%d", &numAn);

  array = calloc(numAn, sizeof(AnimalArrayType));

  for (int i=0; i<numAn; ++i) {

    printf("Enter animal name: ");
    scanf("%s", name);
    printf("Enter their category: ");
    scanf("%s", category);
    printf("Enter age: ");
    scanf("%d", &age);


initAnimal(name, category, age, array + I);

  }

  printf("\n LIST:\n");
  for (int i=0; i<numAn; ++i) {
    printAnimal(array + I);
  }

  return 0;
}


void initAnimal(char *n, char *c, int a, AnimalArrayType *ar)
{
  strcpy(ar->basicInfo.name, n);
  strcpy(ar->basicInfo.category, c);
  ar->basicInfo.age = a;
}


void printAnimal(const AnimalArrayType *stuPtr)
{
      printf("Animal:  %s, Category: %s age %d\n",
      stuPtr->basicInfo.name, stuPtr->basicInfo.category,
      stuPtr->basicInfo.age);
}

AnimalType结构中的char *namechar *category字段被初始化为NULL (从调用calloc() ),但是您没有分配任何char[]内存供它们之后指向,因此您最终当initAnimal()尝试使用strcpy()将数据复制到这些字段时崩溃。

您需要:

  • 将这些字段更改为char[]数组而不是char*指针:
typedef struct {
    char name[20];
    char category[20];
    int age;
} AnimalType;
  • 为它们分配内存以指向,例如从strdup()
typedef struct {
    char *name;
    char *category;
    int age;
} AnimalType;

...

void initAnimal(char *n, char *c, int a, AnimalArrayType *ar)
{
    ar->basicInfo.name = strdup(n);
    ar->basicInfo.category = strdup(c);
    ar->basicInfo.age = a;
}

不要忘记free()使用完成后动态分配的任何内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM