【问题标题】:Passing A Mutable Matrix as Constant Without Warnings在没有警告的情况下将可变矩阵作为常量传递
【发布时间】:2013-03-13 13:18:08
【问题描述】:

我的主函数生成一个矩阵作为值数组“m”,以及另一个指向行开头的指针数组“M”。我想将此矩阵传递给一个子程序,这样就不能修改任何值,也不能修改行指针。即,子程序不得改变矩阵。因此,我将一个指向常量的指针传递给一个常量值。这工作正常。下面的示例会生成预期的错误消息。

#include<stdio.h>
#include<stdlib.h>

void fun(double const * V, double const * const * M)
{
        V = V; // allowed but pointless
        V[0] = V[0]; // not allowed

        M = M; // allowed but 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;
}

错误信息:

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’

这些都符合预期。到目前为止一切顺利。

问题在于传递非常量矩阵也会产生以下警告。我正在使用 gcc v4.5,没有任何选项。

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

请注意,传递向量“V”不会产生此类警告。

我的问题是:我能否将完全可变的矩阵传递给子例程,使其不能被修改、不强制转换且不发出编译器警告?

【问题讨论】:

标签: c pointers constants


【解决方案1】:

这会有所帮助:

void fun(double const * const V, double const * const * const M)
....

您面临的问题是 double const * 不是指向 double 的 const 指针,而是指向 const double 的指针。 double const * == const double *.

不过还是有一条评论:对于序数类型,const 通常不使用说明符。

void fun(double const * V, double const * const * M)
.... // this allows to change V or M, but relaxes caller side

编辑:指针完全是const...所以它们指向的数据不能被修改。

【讨论】:

  • 这没有帮助。 double * const * const 是一个指向 double 的 const 指针的 const 指针。 double * const * 是一个指向 double 的 const 指针。传递其中任何一个都可以很有趣地修改 M 中的值。我需要一个指向 const double 的指针以防止 foo 修改 M。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-10
  • 2011-03-23
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多