I have a structure

struct tree { char name[9]; int count; }; 

when trying to define it in main

 tree.name= "12345678"; 

There is an error

 error C2440: =: невозможно преобразовать 'const char [9]' в 'char [9]' введите сюда код 

Assigned the same way using the symbols '1', '2', '3', etc.

  error C2440: =: невозможно преобразовать 'char' в 'char [9]' 

Created a separate array of sizes [9] and assigned it, but there was an error

 error C2059: синтаксическая ошибка: константа error C2106: =: левый операнд должен быть левосторонним значением 

How can I do everything to assign it and the program did not swear?

  • one
    Why do you need C ++ if you have code sishny? And the tree is a type, not a variable. - αλεχολυτ
  • Read at the same time what is the minimum reproducible example and how to bring it to the question. - αλεχολυτ 6:38 pm
  • struct tree {char * name; int count; }; int main () {tree t; t.name = "13455"; / * etc * / return 0;} - Alexander

3 answers 3

Arrays are not directly assigned!

This is another matter:

 strcpy(tree.name,"12345678"); 

    In your question you are talking about some "definition", but in the code no definition is visible.

    If you really did define a tree object

     tree t; 

    then in this definition you could specify an initializer

     tree t = { "12345678" }; 

    or do the same thing through assignment

     t = { "12345678" }; 

    However, in both cases, the entire object is initialized / assigned, and not a separate field, i.e. t.count is reset.

    You cannot assign a separate bare array. Either use std::strcpy , or replace the char name[9]; on std::array<char, 9> (or even on std::string )

     struct tree { std::array<char, 9> name; int count; }; ... t.name = { "12345678" }; 

    Clang just takes

     t = { "12345678" }; 

    and gcc is not. GCC required

     t = tree{ "12345678" }; 

    Obviously Clang rights ( https://stackoverflow.com/questions/21555026/initializing-stdarraychar-x-member-in-constructor-using-string-literal-gcc )

    • If memory is critical, then std :: array <char, 9> is better - AR Hovsepyan

    If you write like this:

     struct tree { char name[9] = "12345"; int count; }; 

    Here the char name[9] = "123445"; is an array definition. This will not be a mistake. But tree().name = "12345" , this is an assignment, which is already impossible to accomplish (brackets to call the constructor)