Error C2440: '=': cannot convert from 'char [5]' to 'char [20]'

This is due to my previous post.

I created Struct:

struct buffer
{
    char ProjectName[20];
       char ProjectID[20];
};

Now when I try to assign values ​​to it:

buffer buf;
buf.ProjectID = "3174";
buf.ProjectName = "NDS";

I get this error:

error C2440: '=' : cannot convert from 'char [5]' to 'char [20]'

and to solve this, I tried to reduce the size of the structure as shown below (there should be no way to do this):

struct buffer
{

    char ProjectName[4];
    char ProjectID[5];
};

and get error C2106: '=' : left operand must be l-value

+3
source share
5 answers

You need to copy the string to an array:

strcpy(buf.ProjectName, "3174");

Be careful with the length of strings copied to arrays

+7
source

You cannot assign such strings in C ++. To copy a string you need to use a function, for example strcpy. Or better yet, use a classstd::string

+4
source

char ( , sprintf strcpy). C, ++.

++, std::string ( c_str(), , char).

+3

:

buffer buf; 
buf.ProjectID = "3174"; 
buf.ProjectName = "NDS"; 

$2.13.4/1 - " literal " n const char " (3.7)"

"3174" - char const [5], "NDS" - char const [4]. 'buf.ProjectID' 'char const [5]' 'char const [20]'. ++. , .

$8.3.4/5 - [: lvalues ​​ : 4.2. , . 3.10. ] ".

, , lvalue ( , ).

$5.17- " , . lvalue - ".

, :

LValue. Lvalue. , .

+3

, ++ . :

char name[10] = "abcd";

, :

buffer buf = { "NDS", "3174" };

, , .

buf.ProjectName = "abcde";

, ++, - , buf.ProjectName , "abcde". , ProjectName , .

, , ( , ASCIIZ Google), :

strcpy(buf.ProjectName, "name");

ProjectName , , ProjectName, , . - - strncpy(buf.ProjectName, "name", sizeof buf.ProjectName). , , buf.ProjectName , .

++ - C - std::string. :

#include <string>
struct Buffer
{
    std::string project_name_;
    std::string project_id_;
};
Buffer b;
b.project_name_ = "abcde"; // works with string literals.
b.project_id_ = b.project_name_;  // can copy from std::string to std::string
+1

Source: https://habr.com/ru/post/1762432/


All Articles