我正在努力学习更多关于Ackermann功能,递归时间和功能的知识,但是,我的代码不会编译。我感觉它与acktgen()
中的数组有关,但我并非100%确定。
#include <stdlib.h>
#include <iostream>
using namespace std;
int ack(int m, int n){
if(m==0) return n+1;
else if (n==0) return ack(m,1);
else return ack(m-1,ack(m,n-1));
}
int acktgen(const int s, const int t){
int acktable[s+1][t+1];
for (int i = 1 ; i= t+1; ++i){ //column labels
acktable[0][i]= i-1 ;
}
for (int i = 1 ; i= s+1; ++i){ //row labels
acktable[i][0]= i-1 ;
}
for (int i = 1; i<=s+1; ++i){
for (int j = 1; j<=t+1; ++j){
acktable[i][j]= ack(i-1,j-1);
}
}
return(acktable);
}
int main(){
for(int i=0;i<5;i++) {
for(int j=0;j<5;j++) {
cout<<acktgen(4,4)[i][j]<< "\t";
}
}
}
我知道这不是最有效的Ackermann算法,但我只是以它为例。
编译器错误:
prog.cpp: In function 'int acktgen(int, int)':
prog.cpp:26:17: error: invalid conversion from 'int (*)[(t + 1)]' to 'int' [-fpermissive]
return(acktable);
^
prog.cpp:14:6: warning: address of local variable 'acktable' returned [-Wreturn-local-addr]
int acktable[s+1][t+1];
^
prog.cpp: In function 'int main()':
prog.cpp:32:24: error: invalid types 'int[int]' for array subscript
cout<<acktgen(4,4)[i][j]<< "\t";
^
答案 0 :(得分:1)
让我们来看看每个错误和警告:
> prog.cpp: In function 'int acktgen(int, int)': prog.cpp:26:17: error:
> invalid conversion from 'int (*)[(t + 1)]' to 'int' [-fpermissive]
> return(acktable);
你声明你的acktgen
函数返回一个int,但是你要返回一个地址。我不知道你的意图是什么,但如果要从数组中返回一个值,那么你将返回该值,即
return acktgen[0][4];
或类似的东西。
> prog.cpp:14:6: warning: address of local variable 'acktable' returned
> [-Wreturn-local-addr] int acktable[s+1][t+1];
您正在返回本地变量的地址。这样做是C ++中未定义的行为,所以不要这样做。当函数返回时,所有局部变量都会消失。因此,尝试返回(并使用)不存在的东西的地址是行不通的(或者它可能有效,但只是偶然)。
> prog.cpp: In function 'int main()': prog.cpp:32:24: error: invalid
> types 'int[int]' for array subscript
> cout<<acktgen(4,4)[i][j]<< "\t";
这是不正确的,因为acktgen
返回一个int,而不是一个数组或类似数组的对象。
基本上,您需要向我们提供有关您希望在acktgen
函数中返回的内容的更多信息。真的应该是阵列吗?它应该只是一个单一的价值吗?
您的代码中的一些内容:
1)在ANSI中声明具有非常量表达式的数组是不合法的 C ++:
int acktable[s+1][t+1];
这行代码不是合法的C ++。要模拟数组,可以使用std::vector<std::vector<int>>
:
std::vector<std::vector<int>> acktable(s+1, std::vector<int>(t+1));
2)您的循环条件写错:
for (int i = 1 ; i = t+1; ++i){ //column labels
看看中间情况 - 是你想要的,只有i == t+1
时循环才会继续?之后你在循环中犯了同样的错误。
其次,你的循环访问数组越界。 C ++中的数组是基于0的,但是如果你仔细观察你的循环,那么你就会超越边缘:
for (int i = 1; i<=s+1; ++i){
for (int j = 1; j<=t+1; ++j){
acktable[i][j]= ack(i-1,j-1);
}
}
最后一次迭代会发生什么?您访问超出范围的acktable[s+1][t+1]
。该数组的最高索引是s
和t
,因为我们从0开始计数。