字符串/分段错误

2024-06-21

/*                                                                           
  Program to calculate trip and plan flights                                 
*/
#define TRIP 6
#define NAMEMAX 40
#define DEST 1

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


int main(void)
{
  int i, trip_num, row, col;
  char travel_name[TRIP][DEST],
    dest_in[1];


  printf("Please enter the number of trips:");
  scanf("%d", &trip_num);

  while (trip_num > TRIP)
    {
      printf("Invalid number of trip. (Min of 3 trips and Max 6 trips).\n");\
  /*input number of trips*/
      printf("Please enter the number of trips:");
      scanf("%d", &trip_num);
      if (trip_num < TRIP)
        printf("Valid trip number. Please proceed to enter destination code.\
\n");
    }

  for (i=0; i < trip_num ; i++)

    {
      printf("Please enter name of destination(Note: use _ to for spaces in \
name):\n");
      scanf("%s", &dest_in);
      if (strlen(dest_in) < NAMEMAX)
        strcpy(travel_name[i],dest_in);
   /*   else (strlen(dest_in) > NAMEMAX) */



  for (row = 0; row < trip_num; row++)
    {
      for (col=0; col < DEST; col++)
        printf("Trip#:%d travel_name:%s \n", row+1, travel_name[row][col]);
    }

  return 0;
}

我试图让用户将名称作为字符串输入并存储它(如果名称为 40 个字符或更少),但它给了我一个分段错误


trip_num未初始化。不知道 for 循环执行了多少次,因此:

travel_name[i][0]=dest_in[100];

可能会写入超出数组末尾的内容。另外,该声明的目的是什么?我不太明白它想要做什么,所以我会从弄清楚这一点开始。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

字符串/分段错误 的相关文章

随机推荐