[英]Why my code is returning garbage value in C
In the below code I want to reverse the array I created the function arrev() & using while loop to do it在下面的代码中,我想反转我创建的数组 function arrev() & 使用 while 循环来做
#include <stdio.h>
int arrev(int arr[], int revarr[], int N)
{
int start = 0;
while (N > 0)
{
revarr[start] = arr[N];
start++;
N--;
}
}
int print(int arr[], int N)
{
for (int i = 0; i < N; i++)
{
printf("%d\n", arr[i]);
}
}
int main()
{
int arr[10], revarr[10], N;
scanf("%d", &N);
printf("Input String:\n");
for (int i = 0; i < N; i++)
{
scanf("%d", &arr[i]);
}
arrev(arr, revarr, N);
printf("Reversed String:\n");
print(revarr, N);
}
This is my Output这是我的 Output
I am entering the following input: 3 1 2 3 And after reversing I am getting the garbage value as output我正在输入以下输入: 3 1 2 3 反转后,我得到的垃圾值为 output
At least this problem:至少这个问题:
Off-by-one indexing非一索引
int arrev(int arr[], int revarr[], int N)
{
int start = 0;
while (N > 0)
{
// revarr[start] = arr[N];
revarr[start] = arr[N-1];
start++;
N--;
}
}
arr[N] would definitely consist of garbage value. arr[N] 肯定包含垃圾值。
You need to store arr[N-1] not arr[N]您需要存储 arr[N-1] 而不是 arr[N]
correct code:正确的代码:
{
int start = 0;
N--;
while (N >= 0)
{
revarr[start] = arr[N];
start++;
N--;
}
}
It's an OBO这是一个OBO
Change to改成
while (N > 0)
{
N--;
revarr[start] = arr[N];
start++;
}
This is due to indexing issue, In C array starts with 0 goes till N-1.这是由于索引问题,在 C 数组中,从 0 开始一直到 N-1。
In arrev()
you need to decrement N before assigning to reverse array.在
arrev()
中,您需要在分配给反向数组之前减少 N。 this code will work此代码将起作用
int arrev(int arr[], int revarr[], int N)
{
int start = 0;
while (N > 0)
{
N--;
printf(" rev array %d\n", revarr[start]);
printf(" init array %d\n", arr[N]);
revarr[start] = arr[N];
start++;
// printf(revarr[start])
}
}
As a part of best practice, If you're using int as return type, you should use return 0
or use void
as return type.作为最佳实践的一部分,如果您使用 int 作为返回类型,则应使用
return 0
或使用void
作为返回类型。
Also if you want to reverse the array, there is an in-place mechanism which can be achieved.此外,如果您想反转阵列,可以实现就地机制。
void arrev(int arr[], int start, int end)
{
//start = 0
// end = sizeof(arr) - 1
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.