0

I'm initializing a nested array by passing each row separately.

The result is unexpected. See:

(gdb) li
1   #include <stdbool.h>
2   #include <stdio.h>
3   
4   bool sa1[2] = (bool [2]){true,  false};
5   bool sa2[2] = (bool [2]){false, false};
6   bool sa3[2] = (bool [2]){false, false};
7   
8   bool sa[3][2] = {sa1, sa2, sa3};
9   
10  int main() {
(gdb) print sa1
$1 = {true, false}
(gdb) print sa2
$2 = {false, false}
(gdb) print sa3
$3 = {false, false}

So far, all is as expected. However:

(gdb) print sa
$4 = {{true, true}, {true, false}, {false, false}}

I expected the value of sa to contain sa1, sa2 and sa3, but it doesn't.

If I inline those expressions by hand, then it contains the expected values if I compile it with GCC, but not LLVM.

What is going on?

Ivan Perez
  • 582
  • 2
  • 17
  • 1
    Don't you get compiler warnings? – KamilCuk Dec 01 '21 at 17:57
  • First this doesn't have anything to do with gdb, and it's more likely you want to say you compiled with Clang, not LLVM. – user202729 Dec 04 '21 at 07:36
  • Does this answer your question? [Create 2D array from existing 1D arrays in C?](https://stackoverflow.com/questions/31653510/create-2d-array-from-existing-1d-arrays-in-c) – user202729 Dec 04 '21 at 07:43
  • See also: [c++ - creating 2d array from 1d arrays - Stack Overflow](https://stackoverflow.com/questions/13936040/creating-2d-array-from-1d-arrays) – user202729 Dec 04 '21 at 07:43

1 Answers1

1
  bool sa[3][2] = {sa1, sa2, sa3};

It initiates this array with references to arrays sa1, sa1, sa2 converted to bool. And it compiles only because that those references are not NULL pointers thus they convert to true.

In standard C this should not even compile because static storage duration objects *have to be inilized by constant expressions. Variable is not a constant expression so it some king of GCC extensi on

0___________
  • 60,014
  • 4
  • 34
  • 74
  • Yeah, I thought that could be happening. I was trying to check that by printing the pointers, but it wasn't obvious to see. – Ivan Perez Dec 01 '21 at 17:59