问题描述
/*
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个字符以内,但它给了我一个分段错误
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
推荐答案
有许多与你的code的问题。
There are lots of problems with your code.
-
scanf函数(%S,&安培; dest_in)
将读到一个字符串转换成dest_in
这可能会溢出你的缓冲区因为没有大小说明。考虑将其更改为scanf函数(%99秒,dest_in)
让你读99个字符最多,+ 1为空终止为100(阵列大小)。此外,也没有必要使用&放大器;
运营商在这里
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];
您正在访问的字符是dest_in的边界之外。你应该访问的唯一指标为0。
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(旅行#:%d个travel_name:%S \\ n,排+ 1,travel_name [行] [COL]);
您$ ç$ C说,你要打印的字符串。 printf的去寻找一个指向一个字符数组,但 travel_name [行] [COL]
是单个字符。
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 but travel_name[row][col]
is a single character.
而(trip_num&GT; TRIP)
。你告诉用户在3到6之间输入一个号码,但你不检查,如果输入小于3。
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.
这篇关于字符串/分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!