I want to initialize the array car.places[2][3] but there's always zero in the array. Please can someone tell me what I ́m doing wrong, here is the code:
#include <iostream>
#include <string>
using namespace std;
class reserv
{
public:
int places[2][3];
} car;
int main () {
car.places[2][3] = (
(1, 2, 3),
(4, 5, 6)
);
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
cout << i << "," << j << " " << car.places[i][j] << endl;
}
}
return 0;
}
I get this warning form the compiler:
>g++ -Wall -pedantic F_car_test.cpp
F_car_test.cpp: In function 'int main()':
F_car_test.cpp:16:11: warning: left operand of comma operator has no effect [
-Wunused-value]
(1, 2, 3),
^
F_car_test.cpp:16:14: warning: right operand of comma operator has no effect
[-Wunused-value]
(1, 2, 3),
^
F_car_test.cpp:17:11: warning: left operand of comma operator has no effect [
-Wunused-value]
(4, 5, 6)
^
F_car_test.cpp:17:14: warning: right operand of comma operator has no effect
[-Wunused-value]
(4, 5, 6)
^
Thanks in advance,
-
"Theres always zero in the array" What do you mean? You are getting only zero?SandBag_1996– SandBag_19962014年05月07日 18:33:08 +00:00Commented May 7, 2014 at 18:33
-
Never mind! I read it wrong..SandBag_1996– SandBag_19962014年05月07日 18:34:11 +00:00Commented May 7, 2014 at 18:34
-
1You're not initializing the array, you're assigning to it. You can't assign to arrays.Barmar– Barmar2014年05月07日 18:37:39 +00:00Commented May 7, 2014 at 18:37
4 Answers 4
You cannot do it after the declaration without a loop.
Here is how to do it in a loop:
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
car.places[i][j] = 1 + 3 * i + j;
}
}
Comments
You cannot initialize once an object for a struct/class is created; it's called initialization for a reason. Initialize it this way
#include <iostream>
struct reserv
{
int places[2][3];
} car = {{{1, 2, 3}, {4, 5, 6}}};
int main()
{
for(int i = 0; i < 2; ++i)
{
for(int j = 0; j < 3; ++j)
{
std::cout << i << "," << j << " " << car.places[i][j] << std::endl;
}
}
}
Comments
This record
car.places[2][3]
denotes element places[2][3] of data member places of class reserv (or more precisely of object car).
The array was already created as a part of object car that you defined in the global name space.
Write instead
class reserv
{
public:
int places[2][3];
} car = { {
{1, 2, 3},
{4, 5, 6}
} };
Comments
In C++, you can only initialize arrays with initializer lists upon declaration. Since in this case your array is a class member, you can (and should) do it in the constructor.
reserv::reserv():places{{1,2,3},{4,5,6}}{};
You must enable std=c++0x in order to use this.