3

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?

0

2 Answers 2

8

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"}
                       };
Sign up to request clarification or add additional context in comments.

Comments

-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
}

2 Comments

char *movements[][] is invalid, as specified in the question. Also, "need to remember to deallocate it afterwards" is confusing without code.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.