简体   繁体   English

错误:将'char *'分配给'char [4000]'时类型不兼容

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

I've been trying to solve an easy problem, but I can't figure why my program doesn't work. 我一直在尝试解决一个简单的问题,但是我不知道为什么我的程序无法正常工作。 I want to concatenate a string. 我想连接一个字符串。 Can you help me? 你能帮助我吗? If so, can you also explain me why it doesn't work? 如果是这样,您能否也解释一下为什么它不起作用?

#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;
}

strcpy and strcat work directly on the pointer you pass in as the first argument, then also return is so that you can chain calls. strcpystrcat直接在作为第一个参数传入的指针上工作,然后还返回is,以便您可以链接调用。 As such, assigning their result back to the destination pointer is redundant. 这样,将其结果分配回目标指针是多余的。 In this case, it's also invalid, as you can't reassign an array. 在这种情况下,它也无效,因为您无法重新分配数组。

The fix is to just not assign the return value of those calls: 解决方法是不分配这些调用的返回值:

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

However, since you are using C++, you should use std::string instead, which gives you nice value semantics for your string data. 但是,由于您使用的是C ++,因此应改用std::string ,它为您的字符串数据提供了不错的值语义。

you can not do (see 2) 你不能做(见2)

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

because aux is not a pointer, but array. 因为aux不是指针,而是数组。 you can pass it as pointer argument (see 1), but you can not "collect" the result "inside" aux (see 2). 您可以将其作为指针参数传递(请参见1),但不能在内部“辅助”中“收集”结果(请参见2)。

As other suggested, just remove "collection" and it will work as you expect. 正如其他建议一样,只需删除“集合”,它将按您期望的那样工作。

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

Also you are mixing C and C++ in one file. 同样,您将C和C ++混合在一个文件中。

Also probably there is possibility for buffer overflow. 也可能有缓冲区溢出的可能性。

#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;
}

check out definition os strcpy, in should be cin and out should be cout 签出定义os strcpy,in应该是cin,out应该是cout

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM