Why I can not initialize the char array in the structure

I tried to initialize the char array in the structure declaration as follows. But he could not compile the error message. Please let me know why it cannot be compiled.

#include <iostream>

struct A {
    const char value_in_struct[] = "a";  // this line gives me a error message.
};

void t(void) {
    const char value[] = "a";  // this line was ok at compiling
    std::cout << "value = " << value << std::endl;
}

I got the following error message from gcc.

../static_constexpr_array.hpp:16:33: error: initializer-string for array of chars is too long [-fpermissive]
  const char value_in_struct[] = "a";
                                 ^

Thanks, using the time for me.

+4
source share
4 answers

The problem is that the size of the array cannot be deduced automatically from the initializer in the class. The error message generated by clang is perfectly clear (see here ):

prog.cc:4:34: error: array bound cannot be deduced from an in-class initializer
    const char value_in_struct[] = "a"; 
                                 ^

? . , , - ? , (. ):

A a = {"abc"};

, .

(. ).

#include <iostream>

struct A {
    const char value_in_struct[2] = "a";  
};

void t(void) {
    char value[] = "a";
    std::cout << "value = " << value << std::endl;
}
+4

, const char var [] = "something"; , var char , . . 10.

, , .. .

A, const char [], , , . , - , const, , .

, struct - type char * , , .

- , . , , , .

#include <iostream>
using namespace std;

struct B{
    const char mem_var[];
};

struct A {
    const char * value_in_struct ;  // this line gives me a error message.
    A(char *s):value_in_struct(s){}
    A() { value_in_struct = NULL;}
};

void t(void) {
    const char value[] = "att";  // this line was ok at compiling
    std::cout << "value = " << value << std::endl;
    //value[2] = 's';  // gives error
}

int main(){
    A a(const_cast< char *>("abc"));
    A b ;
    b.value_in_struct = "bbc";
    cout <<"a: "<<a.value_in_struct << endl;
    cout <<"b: "<<b.value_in_struct << endl;
    t();
    //B bb; gives error for not initizaling mem_var
    return 0;
}
+1

It has been a while since I used C ++, but can I try:

const char[] value_in_strict = {'a'};
0
source
struct A {
    const char value_in_struct[] = "a";.
};

It is not right. Is this a class member of a class or a member of an object? If it is a member of a class, you should write like this:

static constexpr char value_in_struct[] = "a";

Static because it is a member of the class. Constexpr because you initialize it in the class definition.

If it is a member object, you cannot initialize it in the class definition.

-1
source

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


All Articles