a problem with initialization values of array

Hello everybody!
Can you explain the different between these things?
int a[7] = {a[0] = 1, a[6] = 1};

int a[7] = {[0] = 1, [6] = 1};

int a[7] = {a[0] = a[6] = 1};
by the first method the values of array will be (1,1,0,0,0,0,0)
by the second method - {1,0,0,0,0,0,1}
by the third method - {1,0,0,0,0,0,0}
Why? I can't understand anything!
Because you don't initialize arrays like that.
method 2 shouldn't compile at all
method 1 assigns to the first and the second elements the values of the expressions a[0] = 1 and a[6] =1 and 0 to all other elements
method 3 assigns to the first element the value of the expression a[0] = a[6] = 1 and 0 to the others
http://www.cplusplus.com/doc/tutorial/arrays/
I was hoping C++ could support below initialization syntax like Java did but I cannot get it to compile.

E.g

Java code
String[] p = new String[2]{"0","1"};

C++ code
char *p = new char[2]{'0','1'}; //cannot compile :(
This -> String[] p = new String[2]{"0","1"}; won't compile in Java.
Try:
char *p = {'0','1'};


EDIT: Oops.

-Albatross
Last edited on
Ok my mistake. I just check it is below.

String[] p = new String[]{"0","1"};

:P
char *p = {'0','1'};


error: initializer for scalar variable requires one element
Eh... whoops. Idiot me.
char p[] = {'0','1'};

-Albatross :D
sohguanh wrote:
Ok my mistake. I just check it is below.

Ok then.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str_array[]={"Hello, ","sohguanh! ", ":P :D"};

    cout << str_array[0];
    cout << str_array[1];
    cout << str_array[2];
    cout << endl;

    cin.get();
    return 0;
}
Last edited on
char p[] = {'0','1'};


Thanks. Finally there is C++ equivalent to Java syntax!

But I notice why below does not compile.

char[] p = {'0','1'};

Is the placement of the square brackets important ? Maybe I toggle between Java and C++ and sometimes I get confused cuz I do both language implementation.
sohguanh wrote:
Is the placement of the square brackets important ?

Obviously.
The placement of the square brackets is VERY important. Sorry.

-Albatross
@OP
The answer to your question was in the second paragraph of the tutorial I linked...
Topic archived. No new replies allowed.