gpt4 book ai didi

c++ - 错误 : incompatible types in assignment of 'char*' to 'char [4000]'

转载 作者:行者123 更新时间:2023-11-28 00:14:03 29 4
gpt4 key购买 nike

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

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

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

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

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

关于c++ - 错误 : incompatible types in assignment of 'char*' to 'char [4000]' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31478217/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com