Search code examples
cfunctionpointersmultidimensional-arrayfunction-call

C nested char array change in function with pointers


I have a array and ı want to change with pointers but array is nested char array like char array[][] how can i change the array in function.

char MAP[ROW][COLUMN] = {
    "00000000000000000000",
    "0                  0",
    "0                  0",
    "0                  0",
    "0                  0",
    "0                  0",
    "0                  0",
    "0                  0",
    "0                  0",
    "00000000000000000000",
};

for (int y = 0; y < ROW; y++)
{
    for (int x = 0; x< COLUMN; x++)
    {
        if (MAP[y][x] != '0')
        {
            MAP[y][x] = ' ';
        }
    }
}

I want the change this array in function.


Solution

  • You can declare the function either like

    void change( char MAP[][COLUMN], int row )
    {
        for (int y = 0; y < row; y++)
        {
            for (int x = 0; x< COLUMN; x++)
            {
                if (MAP[y][x] != '0')
                {
                    MAP[y][x] = ' ';
                }
            }
        }
    }
    

    and call it like

    change( MAP, ROW );
    

    And in this case at least the identifier COLUMN must be defined before the function declaration.

    Or if your compiler supports variable length array when

    void change( int row, int column, char MAP[][column] )
    {
        for (int y = 0; y < row; y++)
        {
            for (int x = 0; x< column; x++)
            {
                if (MAP[y][x] != '0')
                {
                    MAP[y][x] = ' ';
                }
            }
        }
    }
    

    and call it like

    change( ROW, COLUMN, MAP );