2011-02-25 131 views
-2
/*                   
    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个字符以内,但它给了我一个分段错误字符串/分段故障

+1

> travel_name [i] [0] = dest_in [100]; < - 不知道这里有什么意图,但是dest_in [100]不是有效的索引。 – Kevin 2011-02-25 20:10:25

回答

1

你的代码有很多问题。

  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.

+0

for the trip num我只使用了1,这样我就可以检查它是否加载(我知道它的马虎)至于scanf当我的意图只是扫描长度为40的字符时,我重新编辑代码,但由于某种原因,当我输入任何名称时,它只会打印第一个字母 – 2011-02-25 20:51:27

3

trip_num不初始化。目前还不清楚有多少次for循环执行这样:

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

可以写过去的数组的末尾。另外,该声明的目的是什么?我并没有真正遵循它正在尝试做的事情,所以我会从头开始。

+0

忘记复制它想要在trip_num中扫描的代码的顶部部分trip_num <6 – 2011-02-25 20:10:23

0

我认为这是因为 - >什么是trip_num

这些类型的问题可以通过使用调试器轻松解决。我可以建议学习gdb(或cgdb),或者也许是一个内置调试功能的Eclipse CDT的直接IDE。