expected primary-expression before ‘[’ token [duplicate] - c++

This question already has answers here:
Why does C++11 not support designated initializer lists as C99? [closed]
(5 answers)
Closed 6 years ago.
I usually use enums to keep two arrays consistent by defining them like following:
enum foo {
ZERO = 0,
ONE,
TWO,
};
int int_array[] = {
[ZERO] = 0,
[ONE] = 1,
[TWO] = 2
};
char *str_array[] = {
[ZERO] = "ZERO",
[ONE] = "ONE",
[TWO] = "TWO"
};
This code compiles fine for c, but throws following error when used in a cpp module.
expected primary-expression before ‘[’ token
Error is for each line in both array declarations. What's the problem here?

The C++ does not support the so-called designator. Initialization that is allowed in C.
So the compiler issues a message.
In C++ you have to write just the following way
int int_array[] = { 0, 1, 2 };
const char *str_array[] = { "ZERO", "ONE", "TWO" };
^^^^^^

It's not valid syntax for C++. You can initialize arrays in following way:
int int_array[] = { 0, 1, 2 };
char *str_array[] = {
"ZERO",
"ONE",
"TWO"
};

Related

C++ What is the difference between the usage of &array and array? [duplicate]

This question already has answers here:
Why is it a compile error to assign the address of an array to a pointer "my_pointer = &my_array"?
(3 answers)
Closed 6 years ago.
Recently, I encountered a problem about using the address of an array when I need to pass it as a reference to another function in C++. For example:
void do_something(float * arr, int size) {
//Will do something about the arr
}
int main () {
float array[] = {1, 2, 3, 4};
do_something(array, 4); // this will work well
do_something(&array, 4); // this will cause error
return 0;
}
But when I try to print out both array and &array, they are the same. Do you guys know what is the reason for this?
Here's a way of doing it with std::vector:
#include <vector>
void do_something(const std::vector<float>& arr) {
// Use arr for whatever.
}
int main() {
std::vector<float> arr = { 1, 2, 3, 4 };
do_something(arr);
return 0;
}
This initializer requires C++11 mode, which most compilers support if that flag is turned on.

Correct and simplest syntactical way to initialise an array to 0 [duplicate]

This question already has answers here:
How to initialize all members of an array to the same value?
(26 answers)
Closed 8 years ago.
I am trying to find out the correct way to initialise an array to all zeros (i.e. as if you have done a memset on the array).
I have found the following methods from various areas in stack overflow (and other sources):
char myArray1[10] = {0};
char myArray2[10] = {0,};
char myArray3[10] = {[0 ... 9] = 0};
char myArray4[10] = {0,0,0,0,0,0,0,0,0,0};
I would prefer the simplest syntax variant... I was using {0}, but I have not found any proof this actually is correct.
Missing elements in an array will be initialised to 0. In addition, C++ allows you to leave the uniform initialiser empty. So the following works, is minimal and also the most efficient:
T array[N] = {};
It’s worth noting that this works for any type T which can be either default-constructed or initialised, not just built-in types. For example, the following works, and will print foo five times:
#include <iostream>
struct foo {
foo() { std::cout << "foo()\n"; }
};
int main() {
foo arr[5] = {};
}
A more extensive list of the different possibilities was posted by aib some time ago.
From the C++ specification, "Aggregate initialization" (8.5.1):
If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from an empty initializer list.
So each char not in the initializer list would be initialized to char() that is 0.
In C++11 you can type:
char a[10] = {};
char b[10]{};
Some old compilers (or was it in C) may require you add at least one member:
char a[10] = {0};
Naturally, if the array has static lifetime (global or static variable), then it will be zero initialized if there is not initializer:
char global_array[10];
I find it confusing, so I prefer to add the = {} anyway.
About the trailing comma, it is useful if you do something like:
char a[] = {
1,
2,
3,
};
So that you don't make a special case for the last line and you make copy&paste and diffs easier. In your specific case is just useless:
char a[10] = {0,};
That comma does nothing, and it is ugly, so I wouldn't write it.
I prefer this because it is simple yet explicit:
char myArray1[10] = { 0 };

Initialization of const array in C++ [duplicate]

This question already has answers here:
initialize a const array in a class initializer in C++
(10 answers)
Closed 9 years ago.
I need to initialize a const int array in a class constructor via initialization list in C++.
I know that there is an easy solution of this problem based on using
extended initialization list.
Still, I want to avoid using -std=c++11 or -std=gnu++11.
Obviously, I know from the beginning that its size is 4 and the
content is {1, 2, 3, 4}.
The only way I can conceive doing this while staying out of the C++11 initializer list realm is to bury it in a struct wrapper and value-initialize it in your construct-initializer list:
#include <iostream>
using namespace std;
struct ArrayWrap
{
int content[4];
int& operator [](size_t n) { return content[n]; }
int operator [](size_t n) const { return content[n]; }
};
static const ArrayWrap content = { {1,2,3,4} };
struct MyObj
{
const ArrayWrap arrwrap;
MyObj() : arrwrap(content) {}
};
int main(int argc, char *argv[])
{
MyObj obj;
for (int i=0;i<4;++i)
cout << obj.arrwrap[i] << ' ';
cout << endl;
return EXIT_SUCCESS;
}
Output
1 2 3 4
It is common in C to bury fixed arrays in structures when returning them from functions by value, and in this case I'm simply exploiting the default copy-ctor of the wrapper struct as-generated by the C++ compiler.
Probably not the ideal solution for what you want, but it does work, and compiles under C++98.
Well, if you're banning C++11 solutions from the candidate set, then you simply cannot do this.

Impossible C++ array indexing [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]
Accessing arrays by index[array] in C and C++
I just found what seems to be a bug in my code, but not only it compiles, it also works as expected initially...
Consider the following code snipet:
#include <string>
#include <iostream>
using namespace std;
class WeirdTest
{
public:
int value;
string text;
WeirdTest() : value(0),
text("")
{}
virtual ~WeirdTest()
{}
void doWeirdTest()
{
value = 5;
string name[] =
{
"Zero",
"One",
"Two",
"Three",
"Four",
"Five"
};
text = value[name];
cout << "text: " << text << endl;
}
};
int main(int argc, char** argv)
{
WeirdTest test;
test.doWeirdTest();
return 0;
}
Instead of having text=value[name]; it should have been text=name[value]; but the compiler does not complain, and the resulting binary code is the exact same whether the "bug" is here or not.
I'm compiling using g++ 4.6.3, and if someone know what is going on here I would be very grateful. Could it be something in the standard that I missed ? Automatic bug-fix in C++0x maybe ? ;)
Thanks a lot,
Cheers !
Yes, that's a curious "feature". Actually what happens is that the compiler translates the a[i] into *(a + i), so array index and array address are actually interchangeable.
Note, it's valid only if operator [] isn't overloaded.

String/char arrays inside struct

I am trying to create a struct that has multiple string arrays inside of it. For my purposes I wanted to use std::string arrays but char * arrays would also work if they can get the job done. Either way I can't figure out how to initialize things. This is what I have:
initialize.h
#include <string>
struct myStruct
{
std::string x[22];
std::string y[8];
};
extern myStruct data[22];
myform.cpp
#include <initialize.h>
#include <string>
myStruct data[22];
data[0].x = {"a", "b", "c", "d", ...};
I am getting errors that look like this:
Error 1 error C2059: syntax error : '{'
Error 2 error C2143: syntax error : missing ';' before '{'
Error 3 error C2143: syntax error : missing ';' before '}'
I have tried various permutations with char * arrays or std::string * arrays instead but to no avail, I am quite stuck. Did I forget something fundamental?
Thanks in advance.
You cannot use the { } array initialization syntax to assign values to arrays. It can only be used when initializing the array right after definition:
int a[3] = { 3, 4, 5 };
but not
int a[3];
a = { 3, 4, 5 }; //error
you will not get around a loop or a manual initialization of every member. But I think the new C++0x standard improves upon this and makes this (and even more initializer syntax) possible.
myStruct data[22];
With the above statement, you have already created 22 objects of type myStruct and each object having it's own x,y string arrays whose size is 22,8 respectively.
You can only initialize each member of an array directly only while declaration and not during assignment operation. So, you can try -
data[0].x[0] = "a";
data[0].x[1] = "b";
// ....
What the error you are doing is something similar to -
int a[5] ;
a = { 1,2,3,4,5 } ; // Error.
int a[] = { 1,2,3,4,5 } ; // Correct.
The
{"a", "b", "c", "d", ...};
syntax is only allowed when defining a variable, so you could do
std::string data[4] = {"a", "b", "c", "d"}; // syntax allowed for definition
but the line
data[0].x = {"a", "b", "c", "d", ...}; // not definition
is not a definition (data[0].x isn't a new variable). Moreover, since this is not a definition, you can't actually place this code outside of a function.
Somewhere in code you're going to have to manually assign each variable (as #Mahesh's answer suggests)
It's not possible to initialize non static array members in C++. Sorry.
If you make these char * instead of strings, you could get away with a static initializer. It's going to be long and ugly though.
struct myStruct
{
char * x[22];
char * y[8];
};
extern myStruct data[22];
myStruct data[22] = {
{ // data[0]
{ "a", "b", "c", ... "v" }, // data[0].x
{ "0", "1", ... "7" } // data[0].y
},
{ // data[1]
...
};
The other comments are correct but I believe there is one other thing you can do. You can initialize the structure when you declare it in your header:
struct myStr
{
string x[22];
string y[8];
} data[22] = { {...}, {...}, ... };
This too will be long and ugly but might address your question. As others have said, you can't extern this and assign to it after instantiation.