Search code examples
cmultidimensional-arrayinitializationbooleancs50

Array has incomplete element type 'bool'


So yeah, this is the error and I'm not sure how to fix this: test.c:5:12: error: array has incomplete element type 'bool []'

This is part of a bigger code but all that's relevant is included.

#include <stdio.h>
#include <cs50.h>

int candidate_count = 3;
bool locked[][] = {locked[0][1] = false, locked[0][2] = false, locked[1][0] = false, locked[1][2] = false, locked[2][0] = false, locked[2][1] = false};


int main(void)
{
    int lockedCount = 0;
    for(int i = 0; i < candidate_count; i++)
        for(int j = 0; j < candidate_count; j++) {
            if(locked[i][j] == false) {
                locked[i][j] = true;
                printf("locked %i vs %i\n", i, j);
            }
            if(i == candidate_count - 2) {
                for(int k = 0; k < candidate_count; k++)
                    if(locked[k][j] == true) {
                        lockedCount += 1;
                        printf("locked %i vs %i\n", i, k);
                    }
                if(lockedCount == 0) {
                    printf("didn't %i vs %i\n", i, j);
                    break;
                }
                else {
                    locked[i][j] = true;
                    printf("locked %i vs %i\n", i, j);
                }
            }
        }
}

Solution

  • These declaration and initialization of an array

    bool locked[][] = {locked[0][1] = false, locked[0][2] = false, locked[1][0] = false, locked[1][2] = false, locked[2][0] = false, locked[2][1] = false};
    

    is incorrect at least because the element of the array type bool[] is an incomplete type.

    You need to write for example like

    bool locked[][3] = 
    {
        { [1] = false, [2] = false },
        { [0] = false, [2] = false }, 
        { [0] = false, [1] = false }
    };
    

    Or alternatively like

    bool locked[][3] = 
    {
        [0] = { [1] = false, [2] = false },
        [1] = { [0] = false, [2] = false }, 
        [2] = { [0] = false, [1] = false }
    };
    

    In fact these declaration and initialization is equivalent to

    bool locked[3][3] = 
    {
        false
    };
    

    because all elements of the array in your declaration are initialized by zeroes that is the value of the macro false..

    Or as the array has static storage duration then it is by default initialized by zeroes. So you could even write

    bool locked[3][3];
    

    And you forgot to include the header <stdbool.h>. It is better to include explicitly headers that are required.

    Here is a demonstrative program.

    #include <stdio.h>
    #include <stdbool.h>
    
    bool locked[][3] = 
    {
        { [1] = false, [2] = false },
        { [0] = false, [2] = false }, 
        { [0] = false, [1] = false }
    };
    
    int main(void) 
    {
        // your code goes here
        return 0;
    }