运行以下C代码后什么都没有打印,什么也不会输出
运行以下C代码后,什么都没有打印,什么也不会输出,我不了解发生了什么,请提供帮助。
此代码检查字符串是否为palindrome。
#include <stdio.h>
#include <string.h>
char *words[] = {"rar", "tokyo", "level", "prefix", "mom", "delhi", "naruto"};
int size = sizeof(words) / sizeof(words[0]);
void palindChecker(char **, int);
int main() {
palindChecker(words, size);
return 0;
}
void palindChecker(char **array, int len) {
char tempStr[10];
for (int i = 0; i < len; i++) {
strcpy(tempStr, strrev(*(array + i)));
if (strcmp(strrev(*(array + i)), tempStr) == 0) {
printf("%s is palindrome\n", *(array + i));
}
else {
printf("%s is not palindrome\n", *(array + i));
}
}
}
nothing is printing after running the below C code , nothing gets outputted, I am not getting understand what is happening, please help.
This code checks if the string is palindrome or not.
#include <stdio.h>
#include <string.h>
char *words[] = {"rar", "tokyo", "level", "prefix", "mom", "delhi", "naruto"};
int size = sizeof(words) / sizeof(words[0]);
void palindChecker(char **, int);
int main() {
palindChecker(words, size);
return 0;
}
void palindChecker(char **array, int len) {
char tempStr[10];
for (int i = 0; i < len; i++) {
strcpy(tempStr, strrev(*(array + i)));
if (strcmp(strrev(*(array + i)), tempStr) == 0) {
printf("%s is palindrome\n", *(array + i));
}
else {
printf("%s is not palindrome\n", *(array + i));
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题:
strrev
对其提供的字符串进行更改,这意味着您正在更改字符串文字,这是不允许的。您的程序可能会崩溃或做其他意外的事情。建议:
tempstr
。const
类型声明数组以表明您不允许更改字符串:示例:
如果您的编译器不支持VLA:S(可变长度阵列),则可以选择适当的内存:
或者,请勿完全反转字符串。通过将开始的开始与末端进行比较,然后“走向中间”,请检查字符串是否是回文。
The issue:
strrev
makes changes to the string you supply to it, which means that you are making changes to string literals, which is not allowed. Your program may crash or do something else unexpected.Suggestions:
tempStr
.const
type to make it clear that you are not allowed to change the strings:Example:
If your compiler does not support VLA:s (variable length arrays),
malloc
ing the appropriate memory could be an option:Alternatively, do not reverse the strings at all. Check if a string is a palindrome by just comparing the beginning with the end and "walk towards the middle":
重新加载时,我知道看到 @ted lyngmo
is_palindrome(const char* str)。
以社区wiki 离开。
strrev(*(array + i)
尝试在就位更改a string literal lirital lirtal“ rar”
。导致不确定的行为(UB)Whihc包括不打印。开始。
On re-loading I know see @Ted Lyngmo good update with
is_palindrome(const char* str)
.Leaving as Community wiki for reference.
strrev(*(array + i)
attempts an in-place change of contents of a string literal like"rar"
. This leads to undefined behavior (UB) whihc includes not printing. Re-code and avoid UB.Instead consider not reversing the string at all and simple compare the end of a spring to the beginning.