String / segmentation fault
/*
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 tri开发者_运维百科ps).\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;
}
I'm trying to get the user to put in a name as string and store it if the name is 40 character or less but its giving me a segmentation fault
trip_num
is not initialized. It is unknown how many times the for loop executes so:
travel_name[i][0]=dest_in[100];
could be writing past the end of the array. Also, what is the purpose of that statement? I don't really follow what it is trying to do so I would start by figuring that out.
There are lots of problems with your code.
scanf("%s", &dest_in)
will read a string intodest_in
which could potentially overflow your buffer because there is no size specifier. Consider changing it toscanf("%99s", dest_in)
so you read 99 characters maximum, + 1 for the null terminator which is 100 (your array size). Also, there is no need to use to&
operator here.travel_name[i][0]=dest_in[100];
You are accessing a character that is outside the bounds of dest_in. The only index you should access is 0.printf("Trip#:%d travel_name:%s \n", row+1, travel_name[row][col]);
Your code says that you want to print a string. printf goes looking for a pointer to a character array buttravel_name[row][col]
is a single character.while (trip_num > TRIP)
. You tell the user to enter a number between 3 and 6 but you don't check if the input is less than 3.
I think it's because --> What is trip_num
?
These types of problems can be easily solved through the use of a debugger. May I suggest learning gdb
(or cgdb
) or perhaps an outright IDE with built-in debugging capabilities like Eclipse CDT.
精彩评论