2

I have the following array structure :

left , right , top
top , left , right 
top , top , left 

I want to declare it in C , I have done it like this :

char *movements[][] = {{"left","right","top"},
                        {"top","left","right"},
                        {"top","top","top"}
                       }

But I am getting this error : array has incomplete element type. What is the right way of achieving this(declaring and accessing (printing)).Do I have to take three dimensional array?

Raulp
  • 7,758
  • 20
  • 93
  • 155

2 Answers2

7

In C, you have to specify the column size when defining a two dimensional array. Take a look at this question: Why do we need to specify the column size when passing a 2D array as a parameter?

char *movements[][3] = {
                           {"left","right","top"},
                           {"top","left","right"},
                           {"top","top","top"}
                       };
Community
  • 1
  • 1
tourniquet_grab
  • 792
  • 9
  • 14
-1

There are multiple ways to declare structures in C. In your particular case, I would declare a 3 by 3 matrix of the form

char *movements[3][3] = {
                          {"left","right","top"  },
                          {"top" ,"left" ,"right"},
                          {"top" ,"top"  ,"top"  }
                        };

If however you do not know the initial size of your array and you wish to fill the array inside a function, you can just declare it

UPDATE:

char ***movements;

And pass it as argument to your function where you can then allocate memory to it and fill it (see example below). You just need to remember to deallocate it afterwards :-)

Here's an example for a vector;

void SomeFunction(char ***ptr_movements){
    int dim = 3;
    **ptr_movements = (char*) malloc(dim*sizeof(char*));

    (*ptr_movements)[0] = "left"; (*ptr_movements)[1] = "right"; (*ptr_movements)[2] = "top";
}

void main(){
    char **movements;
    SomeFunction(&movements);
    // Do something with resulting array
}
  • `char *movements[][]` is invalid, as specified in the question. Also, "need to remember to deallocate it afterwards" is confusing without code. – anatolyg Mar 23 '15 at 11:02
  • Yes thank you, I went over it a bit quickly, I've updated my answer in consequence. However I can't seem to find the right way to deallocate the memory at the end though; free(movements) just gives me an invalid pointer error. – Brieuc de R Mar 23 '15 at 11:58