我正在学习如何递归处理数组的数组。例如,我的程序将 N 个字符串作为输入。然后我构建了一个函数 rev_print
应该再次打印它,但是从最后开始!
#include<stdio.h>
void rev_print(char **, int);
int main(int argc, char *argv[]){
printf("Parametri - argc = %d\n", argc);
int i;
printf("%s\n\n", argv[0]);
for(i = 1; i < argc; i++)
printf("%s\n", argv[i]);
printf("\n");
rev_print(argv, argc);
return 0;
}
/********** AUX ************/
void rev_print(char **p, int n){ /*It should print the array backwards*/
static int i = 0;
if(n >= 2){
rev_print(p, n - 1);
++i;
printf("%s\n", *(p + i));
}
else
printf("%s", *(p + n));
}
我尝试了所有我知道的方法,但现在恐怕我已经知道递归了。 print_rev
将按常规顺序打印数组。
我有一个假设,即我的函数实际上并没有改变字符串的内存位置。我说得对吗?
在 linux 上,我运行程序:
./myProgram.x It is a beautiful day
最佳答案
以相反顺序打印列表的递归比您编写的代码简单得多。简而言之,使用递归以相反顺序打印列表的工作方式如下:
- 如果列表有多个项目,忽略第一个项目并以相反的顺序打印列表的其余部分。
- 打印第一项。
第 1 步是递归步骤。打印列表的其余部分会调用具有不同参数的相同函数。检查结束条件以避免进入无限递归很重要。仅当有“列表的其余部分”要打印时才递归调用该函数。
编码就这么简单:
void rev_print(char **p, int n)
{
# 1. Ignore the first item, recursively print the rest of the list, if any
if (n > 1) {
rev_print(p + 1, n - 1);
}
# 2. Print the first item
printf("%s\n", *p);
}
关于c - 数组数组的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47474915/