error: incompatible types in assignment of 'char*' to 'char [4000]'

error: incompatible types in assignment of 'char*' to 'char [4000]'

我一直在尝试解决一个简单的问题,但我不明白为什么我的程序无法运行。我想连接一个字符串。 你能帮助我吗?如果是这样,你能不能也解释一下为什么它不起作用?

#include <iostream>
#include <cstring>
#include <fstream>

using namespace std;
ifstream in("sirul.in");
ofstream out("sirul.out");
char a[4000]="a",b[4000]="b",aux[4000];
int main()
{ int n,i;
 in>>n;
 if(n==1)out<<"a";
 if(n==2)out<<"b";
 for(i=3;i<=n;i++)
 {
     aux=strcpy(aux,b);
     b=strcat(b,a);
     a=strcpy(a,aux);
 }

    return 0;
}

strcpystrcat 直接在您作为第一个参数传入的指针上工作,然后 return 也可以进行链式调用。因此,将它们的结果分配回目标指针是多余的。在这种情况下,它也是无效的,因为您不能重新分配数组。

解决方法是不分配这些调用的 return 值:

strcpy(aux,b);
strcat(b,a);
strcpy(a,aux);

但是,由于您使用的是 C++,因此您应该改用 std::string,这为您的字符串数据提供了良好的值语义。

#include <iostream>
#include <cstring>
#include <fstream>

using namespace std;
ifstream in("sirul.in");
ofstream out("sirul.out");
char a[4000]="a",b[4000]="b",aux[4000];
int main()
{
 int n,i;
 cin>>n;
 if(n==1)cout<<"a";
 if(n==2)cout<<"b";
 for(i=3;i<=n;i++)
 {
     strcpy(aux,b);
     strcat(b,a);
     strcpy(a,aux);
 }

    return 0;
}

检查定义os strcpy,输入应该是cin,输出应该是cout

你做不到(见2)

char b[4000]="b";
char aux[4000];
aux /* 2 */ = strcpy(aux /* 1 */ , b);

因为aux不是指针,而是数组。您可以将其作为指针参数传递(参见 1),但不能 "collect" 结果 "inside" aux(参见 2)。

正如其他人所建议的,只需删除 "collection",它就会如您所愿地工作。

char b[4000]="b";
char aux[4000];
strcpy(aux /* 1 */ , b);
// or even:
const char *s = strcpy(aux /* 1 */ , b);

您还在一个文件中混合了 C 和 C++。

也有可能是缓冲区溢出