[英]Why my program does not print true result in C
I've found a code about finding longest string in an array and print it with strrev(); 我找到了有关在数组中找到最长字符串并使用strrev()打印的代码。 function.
功能。 My code works successfully, but if my first string was larger than other strings my program does not understand.
我的代码可以成功运行,但是如果我的第一个字符串大于其他字符串,则程序无法理解。
This is my prototype: 这是我的原型:
void LongStr(char str[][50],int n);
and This is my Main() function: 这是我的Main()函数:
int main()
{
char str[size][wsize];
int n;
printf("\n How many words to accept:- ");
scanf("%d",&n);
printf("\n Enter %d words:- \n \n",n);
for(int i = 0; i < n; i++)
scanf("%s", str[i]);
LongStr(str,n);
return 0;
}
and this is my LongStr(); 这是我的LongStr(); function:
功能:
void LongStr(char str[][50],int n)
{
int Max = strlen(str[0]);
int len;
int c;
for(int i = 1; i < n; i++)
{
len = strlen(str[i]);
if( len > Max )
{
c = i;
Max = len;
}
}
printf("\n The longest string with reverse model is: \"%s\" \n \n",strrev(str[c]));
}
Example: 例:
FirstString FirstString
SecondLongestString SecondLongestString
ThirdString ThirdString
output: strrev("SecondLongestString"); 输出:strrev(“ SecondLongestString”);
Example: 例:
FirstString FirstString
SecondString SecondString
ThirdLongestString ThirdLongestString
output: strrev("SecondLongestString"); 输出:strrev(“ SecondLongestString”);
Example: 例:
FirstLongestString FirstLongestString
SecondString SecondString
ThirdString ThirdString
output: crash! 输出:崩溃!
Thanks. 谢谢。
If the longest string is the first c
is never initialized, which makes it garbage and most likely a huge number to index the array. 如果最长的字符串是第一个
c
则永远不会初始化c
,这将使其成为垃圾,并且很可能有大量的数字对数组进行索引。
You should initialize it to 0: 您应该将其初始化为0:
void LongStr(char str[][50],int n)
{
int Max = strlen(str[0]);
int len;
int c = 0;
// ...
}
PS: although this problem doesn't occur with len
, I'd say it's probably good practise to initialize it to something too. PS:尽管
len
不会发生此问题,但我想说也将其初始化为某种东西可能是一个好习惯。 In other words, initializing all variables is a good thing. 换句话说,初始化所有变量是一件好事。 However, I haven't code in
C
in a long time and I'm not sure if this is the norm. 但是,我已经很长时间没有用
C
编写代码了,而且我不确定这是否是规范。
Really simple it's just a missing piece in your code 真的很简单,这只是代码中的一部分
int Max = strlen(str[0]);
int len;
int c;
You need to give the c
a value that why it's not working because it doesn't have a base value so try to change your code to 您需要为
c
一个值,说明为什么它不起作用,因为它没有基值,因此请尝试将代码更改为
int Max = strlen(str[0]);
int len;
int c = 0; // base value of 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.