user3262424
user3262424

Reputation: 7489

C -- changing a multi-dimensional array to CONST in a function?

I have the following c function declaration:

float Sum2d( const unsigned int nRows, const unsigned int mCols, float arr[nRows][mCols] )
{
    float sumAll = 0;

    // I would like to make this change illegal! 
    arr[0][0] = 15;

    for (int i = 0; i < nRows; i++)
        for (int j = 0; j < mCols; j++)
            sumAll += arr[i][j];

    return sumAll;
}

Using the code:

int main()
{
    // define a 2d float array
    float myArr2d[3][2] = {{1,2}, {3,4}, {5,6}};

    // calculate the sum
    float sum = Sum2d(3, 2, myArr2d);

    // print the sum
    printf("%f\n", myOpResult);

    // return 1
    return 1;
}

This function works well, yet there's one problem: the elements of arr can be altered in the Sum2d() function.

How can I change Sum2d()'s prototype to prevent any changes to arr's elements?

Upvotes: 1

Views: 947

Answers (3)

Jens Gustedt
Jens Gustedt

Reputation: 78993

Multidimensional arrays with const qualification are difficult to handle. Basically you have the choice to cast non-const arrays at every call side, to avoid such const arrays as arguments completely, or to deviate by using some sophisticated macros. This is a longer story, you may read it up here.

Upvotes: 3

ASD
ASD

Reputation: 15

Change the prototype of the function to use const with float

Also you have specified nRows / nCols in array argument, which is not allowed in C. If you don't know the bounds of array, use double pointer.

This approach doesn't prevents typecasting in the function.

#include <stdio.h>

float Sum2d( const unsigned int nRows, const unsigned int mCols, const float arr[][2] )
{
    float sumAll = 0;

    // I would like to make this change illegal! 
    //arr[0][0] = 15;

    for (int i = 0; i < nRows; i++)
        for (int j = 0; j < mCols; j++)
            sumAll += arr[i][j];

    return sumAll;
}

int main()
{
    // define a 2d float array
    float myArr2d[3][2] = {{1,2}, {3,4}, {5,6}};

    // calculate the sum
    float sum = Sum2d(3, 2, (const float (*)[2])myArr2d);

    // print the sum
    printf("%f\n", sum);

    // return 1
    return 1;
}

Since you are using following command line i suppose:

gcc <file.c> -o out -std=c99

Running on Debian Squeeze
$ gcc array.c -o array -std=c99

$ gcc --version       
gcc (Debian 4.4.5-8) 4.4.5
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO   
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.             

Upvotes: -2

Carey Gregory
Carey Gregory

Reputation: 6846

I don't know what compiler you're using, but that doesn't compile for me as C or C++.

But regardless, just making arr const should suffice.

Upvotes: 1

Related Questions