1

The program crashes right in the instruction mentioned in the source code (I didn't write all the code because it's too long)

int main()
{
char screen[24][80];

//......every thing is well until this instruction

backgrounds(5,screen);

//......the program doesn't execute the rest of the code

}
//______________________________________________________

//this is a header file

void backgrounds(int choice,char **screen)
{   
    if(choice==5)
    {
        screen[18][18]='-';
        screen[18][19]='-';
        screen[18][20]='-';
    }
}
heiwiper
  • 13
  • 3

1 Answers1

3

A char [24][80] cannot be converted to a char **.

When passed to a function, an array decays into a pointer to its first element. This is simple for a 1 dimensional array, but less so for higher dimensions.

In this case, a char [24][80] is an array of char [80]. So passing a variable of this type to a function yields a char (*)[80].

Change your function definition to either this:

void backgrounds(int choice,char (*screen)[80])

Or this:

void backgrounds(int choice,char screen[24][80])

Or you can use a variable length array for maximum flexibility:

void backgrounds(int choice, int x, int y, char screen[x][y])
dbush
  • 205,898
  • 23
  • 218
  • 273
  • "This is straightforward for a 1 dimensional array, but not for higher dimensions." - That's wrong. It is very well straight-forward: It decays to a pointer to an array of one less dimension: a 2D array decays to a pointer to a 1D array, a 3D array to a pointer to 2D array, etc. As you wrote: an array decays to a pointer to its element. An element of a (n)D-array is an (n-1)D array. With a 0D array being a single element. – too honest for this site Nov 30 '16 at 22:31
  • @Olaf "straightforward" probably wasn't the best choice of words. Changed to "simple". – dbush Nov 30 '16 at 23:21
  • I'm still not happy with this. Maybe I'm too deep into this, but to me it as both, straight-forward and obvious: an array always decays to a pointer to the first element. There is no exception how many dimensions. Actually the confusion is that ppl don't stop after this decaing, but think it recurses to the next dimension and so on. But that's **not** obvious to me. Anyway, I don't intend to DV for this, so feel free to ignore my comment :-) – too honest for this site Nov 30 '16 at 23:24
  • I would just say 'do this' and have the direct [24][80] version – pm100 Nov 30 '16 at 23:29
  • 1
    @pm100: Agreed with a slight modification: No magic numbers. Either a VLA with dimensions passed (most flexible) or macros with the constants. – too honest for this site Nov 30 '16 at 23:32