[英]I tried reversing a string in C without using <string.h> functions, it didn't work
I was trying to inverse a string in c which seemed fairly easy at first but I keep encountering some weird problem that I don't seem to understand where it comes from.我试图在 c 中反转一个字符串,这起初似乎很容易,但我一直遇到一些奇怪的问题,我似乎不明白它来自哪里。
The string c3 keep showing more characters that it should字符串 c3 继续显示它应该显示的更多字符
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c1[10];
char c3[10];
int i,j,l;
printf("donner la chaine a inverser\n");
fflush(stdin);
gets(c1);
for(i = 0; c1[i] != '\0'; i++)
{
}
l = i;
j = 0;
for(i = l-1; i >= 0; i--)
{
printf("%d%d\n", i, j);
c3[j] = c1[i];
j++;
}
printf("%s", c3);
return 0;
}
I'm not really sure but c3 should only have the number of characters that c1 does but it shows that it contains more in printf("%s", c3);
我不太确定,但 c3 应该只有 c1 的字符数,但它表明它在
printf("%s", c3);
包含更多字符printf("%s", c3);
. .
I am still new to strings in c so I probably missed something really obvious.我对 c 中的字符串还是陌生的,所以我可能错过了一些非常明显的东西。
The answer is quite simple.答案很简单。 let's say your string is abcdef.
假设您的字符串是 abcdef。 in c3, you will put fedcba, where a in at index 5.
在 c3 中,您将放置 fedcba,其中 a 位于索引 5 处。
What will be at index 6 ?索引 6 会是什么? The answer is "no one knows".
答案是“没有人知道”。 it's undefined.
它是未定义的。 That's why you have garbage after your string.
这就是为什么你的字符串后面有垃圾的原因。
In C, a string is a char array, "null terminated" ( NULL terminated means there is the character '\\0'
after the last character ( or simply a 0
( not '0'
) ).在 C 中,字符串是一个字符数组,“空终止”(空终止意味着在最后一个字符之后有字符
'\\0'
(或者只是一个0
(不是'0'
))。
The simple way of solving your problem is to initialize c3 to 0.解决问题的简单方法是将 c3 初始化为 0。
char c3[10] = {0};
This way, your array will be filled with NULL characters.这样,您的数组将填充为 NULL 字符。
You did not set a null terminator at offset c3[i]
.您没有在偏移
c3[i]
处设置空终止符。 printf()
will keep reading from c3
until it finds a null byte, since c3
a local object that is not initialized, printf
may read and output extra characters as you experience, and potentially read beyond the end of the array which has undefined behavior. printf()
将继续从c3
读取,直到找到一个空字节,因为c3
是一个未初始化的本地对象,所以printf
可能会读取和输出额外的字符,并且可能会读取到具有未定义行为的数组末尾之外。
Note also that you should not use gets()
as you cannot tell this obsolete C library function the size of the destination array.另请注意,您不应使用
gets()
因为您无法告诉这个过时的 C 库函数目标数组的大小。
Here is a modified version:这是一个修改后的版本:
#include <stdio.h>
int main() {
char c1[80];
char c3[80];
int i, j, len;
printf("donner la chaine a inverser:\n");
fflush(stdin);
if (!fgets(c1, sizeof c1, stdin))
return 1;
for (len = 0; c1[len] != '\0' && c1[len] != '\n'; len++)
continue;
for (j = 0, i = len; i-- > 0; j++) {
c3[j] = c1[i];
}
c3[j] = '\0'; // set the null terminator
printf("%s\n", c3);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.