字符串/分段错误

/* Program to calculate trip and plan flights */ #define TRIP 6 #define NAMEMAX 40 #define DEST 1 #include  #include  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) */ 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个字符或更少,但它给我一个分段错误

您的代码存在很多问题。

  1. scanf("%s", &dest_in)会将一个字符串读入dest_in ,这可能会使缓冲区溢出,因为没有大小说明符。 考虑将其更改为scanf("%99s", dest_in)这样您最多可读取99个字符,空终止符为100(数组大小)为+ 1。 此外,这里不需要使用&运算符。

  2. travel_name[i][0]=dest_in[100]; 您正在访问一个超出dest_in范围的字符。 您应该访问的唯一索引是0。

  3. printf("Trip#:%d travel_name:%s \n", row+1, travel_name[row][col]); 您的代码表示您要打印字符串。 printf寻找指向字符数组的指针,但travel_name[row][col]是一个单个字符。

  4. while (trip_num > TRIP) 。 您告诉用户输入3到6之间的数字,但不检查输入是否小于3。

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

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

可能是写过数组的末尾。 此外,该声明的目的是什么? 我并没有真正遵循它想要做的事情,所以我首先要弄清楚这一点。

我想是因为 – > trip_numtrip_num

通过使用调试器可以轻松解决这些类型的问题。 我是否可以建议学习gdb (或cgdb ),或者使用内置调试function(如Eclipse CDT)的完全IDE。