[英]Why is both my input array and output array corrupted when I try to implement a function to reverse the array?
I'm Programming in C, using Linux GCC Compiler. 我正在使用Linux GCC编译器进行C语言编程。 I'm very much new to programming.
我对编程非常陌生。
I'm confused as to why my in[] char array would be changed at all in the function. 我对为什么在函数中完全更改in [] char数组感到困惑。 Doesn't the code simply count the amount of subscripts in in[] and then copy its contents into out[] but backwards?
代码难道不只是简单地计算in []中的下标数量,然后将其内容复制到out []中而是向后复制吗? How is it being changed in the function?
如何在功能中进行更改?
/*reverse in to out*/
void reverse(char in[], char out[]) {
int i, l,b;
b = i = l = 0;
while (in[i] != '\0')
++i;
for(l=i;l > 0; l--) {
in[l] = out[b];
++b;
}
return;
}
Your assignment statement is backwards. 您的分配声明是向后的。
in[l] = out[b];
Means "Assign the value in array out
at index b
to array in
index l
". 意味着“分配在阵列的值
out
在索引b
到阵列in
的索引l
”。 This line should instead be 该行应改为
out[b] = in[l];
And BTW, you don't need an empty return
statement, you can simply omit this in a void
function. 顺便说一句,您不需要空的
return
语句,只需在void
函数中省略此语句即可。
for(l=i-1;l >= 0; l--) {
out[b] = in[l];
++b;
}
out[b] = '\0';
Four problems fixed: start at i-1
, test for l>=0
, reverse the assignment, and terminate out with a null character. 解决了四个问题:从
i-1
开始,测试l>=0
,逆转分配,并以空字符终止。
Also, a good idea is to use const
when a function argument will not be changed. 另外,一个好主意是在不更改函数参数时使用
const
。 In this case, const char in[]
would let you spot the assignment error because the compiler would give you a compile time error. 在这种情况下,
const char in[]
将使您发现分配错误,因为编译器将为您提供编译时错误。
You can use strlen : 您可以使用strlen:
for(l=strlen(in), b=0; l>=0; l--)
out[b++] = in[l];
// ensure null terminated so strlen out works
out[b] = '\0';
This assumes out is wide enough for in AND in is null terminated 这假定out足够宽,并且in终止为null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.