这段代码的重点是使用递归函数来反转数组。
例如:arr = 1, 2, 3
输出应为3, 2, 1
这是我想出的代码。
我想知道我的思考过程是否有问题。
#include <stdio.h>
void rReverseAr(int ar[], int size);
int main()
{
int array[80];
int size, i;
printf("Enter size: \n");
scanf("%d", &size);
printf("Enter %d numbers: \n", size);
for (i = 0; i < size; i++)
scanf("%d", &array[i]);
printf("rReverseAr(): ");
rReverseAr(array, size);
for (i = 0; i < size; i++)
printf("%d ", array[i]);
printf("\n");
return 0;
}
void rReverseAr(int ar[], int size)
{
int temp[size], i = 0;
if (size == 1)
temp[i] = ar[size-1];
else {
temp[i] = ar[size-1];
i++;
rReverseAr(ar, size-1);
}
for (i = 0; i < size; i++)
ar[i] = temp[i];
}
答案 0 :(得分:1)
您要求的想法和代码有误。
您并不是在寻求代码解决方案,我非常尊重。
因此,这是您的功能未更改的代码,其中包含您应考虑的注释。
#include <stdio.h>
void rReverseAr(int ar[], int size);
int main()
{
int array[80]; /* with this array you should make sure
that users size is <=80 */
int size, i; /* always initialise your variables */
printf("Enter size: \n");
scanf("%d", &size); /* always check the return value of scanf(),
the return value, not the scanned value */
printf("Enter %d numbers: \n", size);
for (i = 0; i < size; i++)
scanf("%d", &array[i]); /* return value ... */
printf("rReverseAr(): ");
rReverseAr(array, size);
for (i = 0; i < size; i++)
printf("%d ", array[i]);
printf("\n");
return 0;
}
void rReverseAr(int ar[], int size)
{
int temp[size], i = 0;
/* quoting Johnathan Lefflers comment:
You should be able to reverse the array in situ
without needing the temporary array temp in the function
- even when using recursion. */
if (size == 1)
temp[i] = ar[size-1]; /* reconsider the necessity to reverse an array of size 1 */
else {
temp[i] = ar[size-1]; /* you overwrite index 0,
don't you think you still need it?
Think back to when you learned how to swap
the values of two variables...
Even swapping by copying into a temp array,
you still need to do something about the
other value.
Even if you do not actually attempts to swap
two values and only intend to go recursively
through the array and only move one end, you need
to move the end which you actually modified. */
i++; /* you increase something which then is never used again... */
rReverseAr(ar, size-1); /* After swapping (assuming successfully) the
first and last element, do you really want
to swap the array which begins with the same,
already swapped, first element ?
Remember that increasing i does not have an
effect on this... */
}
for (i = 0; i < size; i++) /* only necessary because of the temp array decision... */
ar[i] = temp[i];
}
(我也很同意Johnathan Lefflers的第二条评论,
我不认为这是引用... )