c - Passing A Mutable Matrix as Constant Without Warnings -


my main function generates matrix array of values "m", , array of pointers start of rows "m". want pass matrix subroutine such no values can modified, , such no row pointers can modified. i.e., subroutine must not alter matrix. such, pass pointer constant pointer constant value. works fine. expected error messages generated example below.

#include<stdio.h> #include<stdlib.h>  void fun(double const * v, double const * const * m) {         v = v; // allowed pointless         v[0] = v[0]; // not allowed          m = m; // allowed pointless         m[0] = m[0]; // not allowed         m[0][0] = m[0][0]; // not allowed }  int main() {         double *v = (double *)malloc(2*sizeof(double));         double *m = (double *)malloc(4*sizeof(double));         double **m = (double **)malloc(2*sizeof(double *));          m[0] = &m[0];         m[1] = &m[2];          fun(v,m);          return 0; } 

error messages:

test.c: in function ‘fun’: test.c:7:2: error: assignment of read-only location ‘*v’ test.c:9:2: error: assignment of read-only location ‘*m’ test.c:10:2: error: assignment of read-only location ‘**m’ 

these expected. far.

the problem passing non-constant matrix generates following warning. i'm using gcc v4.5 no options.

test.c: in function ‘main’: test.c:22:2: warning: passing argument 2 of ‘fun’ incompatible pointer type test.c:4:6: note: expected ‘const double * const*’ argument of type ‘double **’ 

note passing vector "v" generates no such warnings.

my question this: can pass mutable matrix subroutine in such way cannot modified, without casting, , without compiler warnings?

this help:

void fun(double const * const v, double const * const * const m) .... 

the problem facing double const * not const pointer double, pointer const double. double const * == const double *.

however there still 1 comment: ordinal types const specifiers not used.

void fun(double const * v, double const * const * m) .... // allows change v or m, relaxes caller side 

edit: pointers made totally const... data point can't modified.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -