首页 文章

strcpy从struct char *到另一个struct char * - 分段错误[关闭]

提问于
浏览
0

我似乎在将一个char数组从struct复制到另一个struct中的另一个char数组时遇到了问题 . 我得到一个分段错误,我认为它与在struct中为我的char数组分配内存有关 . 但有人可以确定导致核心倾销的确切点 .

struct match 
{
  char *day;
  char *date;
  char *hour;
  char *home_side;
  char *visitors;
  int home_result;
  int visit_result;
  int spectators;
  int rounds;
  int result;
};

struct team
{
  char *name;
  int victory_visit;
  int victory_home;
  int home_visitors;
};

typedef struct match match;
typedef struct team team;

然后我有填充称为匹配的结构的函数

void scan_matches(match *all_matches)
{
  int i = 0, counter = 1, round_number = 1;;
  FILE *ifp = fopen("kampe.txt","r");
  char line[LINE_MAX];

  while(fscanf(ifp," %[^\n]", line) == 1)
  {
    int thousand, hundreds;
    sscanf(line,"%s %s %s %s - %s %d - %d %d.%d", &all_matches[i].day, &all_matches[i].date, &all_matches[i].hour, &all_matches[i].home_side, &all_matches[i].visitors,
      &all_matches[i].home_result, &all_matches[i].visit_result, &thousand, &hundreds);
    all_matches[i].spectators = ((thousand * 1000) + hundreds);
    round_number = create_rounds(all_matches, counter, i, round_number);
    counter++;
    i++;
  }
  fclose(ifp);
}

之后是导致我麻烦的功能 . 我希望将char * homeside从match struct复制到team struct中的char * name的函数 .

void load_teams(match *all_matches, team *all_teams)
{
  int i, j = 0;
  for(i = 0; i < 6; i++)
  {
    strcpy(all_teams[j],all_matches[i].home_side);
    j++;
    strcpy(all_teams[j],all_matches[i].home_side);
    j++;
  }
  for(i = 0; i < 12; i++)
  {
    printf("%s\n",all_teams[j].name);
  }
}

3 回答

  • 1

    scanf 将不会分配内存,它会尝试写入已分配的缓冲区(对于您使用的所有%s参数) .

    由于这些指针是垃圾(从未分配), memcpystrcpy 将因seg故障而失败 .

  • 0

    您的:

    struct match 
    {
      char *day;
      //...
    

    有指向字符的指针,但没有存储来存储这些字符 . 因此,当你阅读它们时,sscanf在某个未确定的地方,这可能不是你的,所以操作系统会中止你的程序 .

    将它们声明为字符数组,或让sscanf将它们读入足够大小的缓冲区,然后确定其长度,然后使用 malloc 分配存储并将缓冲区复制到该存储 .

  • 0

    all_matches和all_teams未声明为数组

    void load_teams(匹配* all_matches,team * all_teams)

    所以你不能用这个:

    strcpy(all_teams [j],all_matches [i] .home_side); j;的strcpy(all_teams [j]时,all_matches [I] .home_side); j;

    你的函数应该像这样声明:

    void load_teams(match **all_matches, team **all_teams)
    

    同样的评论:

    void scan_matches(match **all_matches)
    

相关问题