lbs0912
lbs0912

Reputation: 331

Output elments of a two-dimension array

I come across the problem:

I want to output elements of a two-dimension array,just like this

char cur[3][3] = {{'.','.','B'},{'B','W','.'},{'B','.','.'}};
for(int x=0;x<3;x++){
   for(int y=0;y<3;y++){
       cout<<cur[x][y];
   }
   cout<<endl;
} 

This works fine. But I also come across the follwing method

for(int x=0;x<3;x++){
    cout<<cur[x]+1<<endl;
}

Why the method work well? I can not understand the method. Can someone help me to explain it? Thank you.

Upvotes: 1

Views: 55

Answers (2)

lapinozz
lapinozz

Reputation: 310

I don't see how the second method could "work". It invokes undefined behavior because you are basically passing non-null-terminated char pointer.

When you call cur[0][0] it's the same as calling *(*(cur + 0) + 0) and so calling cur[0] + 1 is the same as *(cur + 0) + 1 which returns a pointer to the second element of the first subarray.

When you give a char pointer to cout, it will print each char it finds until it hits a 0, then it stops. Let's say that by any chance there is a zero at the end of each subarray, it will print the second element, then the third, then stop, and do that for each subarray.

Upvotes: 2

Amadeus
Amadeus

Reputation: 10655

In the second method, you only stop printing when you find a null mark `\0', otherwise, it will continuous printing whatever if founds in memory.

You can easily see this happening changing a bit your code:

char cur[3][3] = {{'.','.','B'},{'B','W','\0'},{'B','.','.'}};
for(int x=0;x<3;x++){
    cout<<cur[x]+1<<endl;
}

Now it prints:

.BBW
W
..

Upvotes: 1

Related Questions