Thanks for asking question, when you state const char var[] = "something";
it means , you are declaring variable var of array of char type with length same as its assigned with string at initialization. eg. for above case its 10.
The statement will go valid when you can initialize variable, ie when you declare it in main or any other function.
Now your struct part of code is declaring a struct A in which you are declaring variable or const char [] in it, here you cannot initialize it, hence error. Also if you declare struct with such member variable and try to create instance it will give compilation error since its const type and we need to initialize it at creation of instance which is not possible.
Work around for it is in struct have member variable as type char * and assign it accordingly , this way you will be able to achieve what you looking for.
I tried some code on same lines and commented with lines it will give compilation error.. please see , hope it helps.
#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;
}
const char[].Aobject, but, if the such code were possible, the size ofvalue_in_structcould change depending on how it was initialised (e.g. copy or default initialisation). Hopefully someone else can elaborate with a quote from the standard.