Static arrays and sizeof
-
Why can't I use sizeof to find the size of a static data array within a class. It works fine if I use sizeof outside the class. class myclass { public: static char myarray[]; void myfunction() { // VC6 compile error: illegal sizeof operand // GCC 3.2 'sizeof' applied to incomplete type 'char []' // cout << sizeof (myarray); } }; char myclass::myarray[] = "this is a string"; int main(int argc, char* argv[]) { myclass mc; cout << sizeof(mc.myarray); // works //mc.myfunction(); return 0; } another alternative I tried was to make the array const but this only works using GCC on linux; using VC6 I get errors. class myclass2 { public: //VC6 error C2258: illegal pure syntax, must be '= 0' //VC6 error C2252: 'myarray' : pure specifier can only be specified for functions static const char myarray [] = "this is another string"; void myfunction() { cout << sizeof(myarray); } }; int main(int argc, char* argv[]) { myclass2 mc2; cout << sizeof(mc2.myarray); // works mc2.myfunction(); return 0; } Thanks if anyone can help.
-
Why can't I use sizeof to find the size of a static data array within a class. It works fine if I use sizeof outside the class. class myclass { public: static char myarray[]; void myfunction() { // VC6 compile error: illegal sizeof operand // GCC 3.2 'sizeof' applied to incomplete type 'char []' // cout << sizeof (myarray); } }; char myclass::myarray[] = "this is a string"; int main(int argc, char* argv[]) { myclass mc; cout << sizeof(mc.myarray); // works //mc.myfunction(); return 0; } another alternative I tried was to make the array const but this only works using GCC on linux; using VC6 I get errors. class myclass2 { public: //VC6 error C2258: illegal pure syntax, must be '= 0' //VC6 error C2252: 'myarray' : pure specifier can only be specified for functions static const char myarray [] = "this is another string"; void myfunction() { cout << sizeof(myarray); } }; int main(int argc, char* argv[]) { myclass2 mc2; cout << sizeof(mc2.myarray); // works mc2.myfunction(); return 0; } Thanks if anyone can help.
myarray must be defined before it is used as a parameter to sizeof, so you can't use it inside a class definition. compiler needs to see the definiton of the array to know its size. Define the function in cpp file, after the myarray definition:
// in cpp file, after "char myclass::myarray[] = "this is a string";" void myclass::myfunction() { cout << sizeof (myarray); };
-
myarray must be defined before it is used as a parameter to sizeof, so you can't use it inside a class definition. compiler needs to see the definiton of the array to know its size. Define the function in cpp file, after the myarray definition:
// in cpp file, after "char myclass::myarray[] = "this is a string";" void myclass::myfunction() { cout << sizeof (myarray); };
:):):):):):):):):):):):):):)