cfunctionarguments

#define COLUMNS as a function argument in C


It is more question than a problem. I make my header file with a function declaration like this:

void fw_iteracja_wsk_rows_a(float (*tab)[COLUMNS], int ROWS);

How can I adjust/change the COLUMNS value depending on the array size in other files?

Currently, no matter what I try, COLUMNS takes the value from the header file, making the function not universal.

To be clear im using VS2022 with my travel to learn C. This is a definition of the function:

void fw_iteracja_wsk_rows_a(float (*tab)[COLUMNS], int ROWS)
{
    float (*p_rows)[COLUMNS];
    float* p_columns;
    p_rows = tab;
    p_columns = *p_rows;
    for (p_rows; p_rows < tab + ROWS; p_rows++)
    {
        for (p_columns; p_columns < *p_rows + COLUMNS; p_columns++)
        {
            printf("%.1f, ", *p_columns);
        }
        printf("\n");
    }
}

Declaration is in file: C_PATMY_2DARRAY.h Also in this file is: #define COLUMNS 12. Definition is in file: C_PATMY_2DARRAY.c

When I #include "C_PATMY_2DARRAY.h in other .c file and try to use this function with array with diffrent columns number. I cant becouse function is getting COLUMNS value form header file. I did try #ifndef #undef but it is not working.

Grateful for the tip.

@babon - i can agree with overcomplicating. But, did it becouse i need this pointer on array: float (*tab)[COLUMNS] for being able to make iteration with pointers.

Maybe someone can tell me how to declare universal functions using a pointer to an array. When I need to specify the number of columns in the declaration and definition.


Solution

  • The normal way in standard C would be to not use a fixed constant, but to pass the array sizes along as parameters:

    void func (int rows, int cols, float tab[rows][cols])
    {
      ...
      tab[i][j] = something;
    }
    

    And since array parameters get adjusted to a pointer to the first element, that's 100% equivalent to:

    void func (int rows, int cols, float (*tab)[cols]);
    

    This works on any decent C compiler released after year 1999.


    The next problem is that VS2022 is not a decent C compiler and it is using an older standard even than the one from year 1999. So it won't support modern standard C.

    On such very old and outdated compilers, you would have to resort to "mangled 2D arrays", ie represented as a 1D array:

    void func (int rows, int cols, float* tab)
    {
     ...  tab[i*cols + j] = something;
    }
    

    Alternatively investigate how to set VS to use gcc or clang instead of outdated MSVC.