【问题标题】:Why i can't compile without declare a matrix like const为什么不声明像 const 这样的矩阵就无法编译
【发布时间】:2013-02-20 16:33:06
【问题描述】:

我的疑问是:为什么在这段代码中:

/*Asignacion de valores en arreglos bidimensionales*/
#include <stdio.h>

/*Prototipos de funciones*/
void imprimir_arreglo( const int a[2][3] );

/*Inicia la ejecucion del programa*/
int main()
{
  int arreglo1[2][3] = { { 1, 2, 3 }, 
                     { 4, 5, 6 } };                         
  int arreglo2[2][3] = { 1, 2, 3, 4, 5 };
  int arreglo3[2][3] = { { 1, 2 }, { 4 } };

  printf( "Los valores en el arreglo 1 de 2 filas y 3 columnas son:\n" );
  imprimir_arreglo( arreglo1 );

  printf( "Los valores en el arreglo 2 de 2 filas y 3 columnas son:\n" );
  imprimir_arreglo( arreglo2 );

  printf( "Los valores en el arreglo 3 de 2 filas y 3 columnas son:\n" );
  imprimir_arreglo( arreglo3 );

  return 0;
}  /*Fin de main*/

/*Definiciones de funciones*/
void imprimir_arreglo( const int a[2][3] )
{
  int i;  /*Contador filas*/
  int j;  /*Contador columnas*/

  for (i = 0; i <=1; i++)
  {
    for (j = 0; j <= 2; j++)
    {
      printf( "%d ", a[i][j] );
    }

    printf( "\n" );
  }
} /*Fin de funcion imprime_arreglo*/

如果不声明 const 之类的矩阵变量,我就无法编译,而在向量中我可以...为什么会出现这种行为?对不起,如果我的英语不好,我会说西班牙语。非常感谢您的回答。

【问题讨论】:

  • 什么?你的意思是函数参数?我想你可以,错误是什么?
  • 我的编译器告诉我必须修改数组的类型,但这种行为只发生在矩阵而不是向量中,我想知道为什么?

标签: c vector matrix constants


【解决方案1】:

这个话题真的很乱。您不应该对间接指针使用常量修饰符,例如const int**,因为可能会出现混乱,例如:

  1. int **不能修改值吗?

  2. 或者,它是const int *的指针(甚至是数组)吗?

有一个topic about it on C-faq

例子:

const int a = 10;
int *b;
const int **c = &b; /* should not be possible, gcc throw warning only */
*c = &a;
*b = 11;            /* changing the value of `a`! */
printf("%d\n", a);

它不应该允许更改 a 的值,gcc 允许,clang 运行时出现警告但不会更改值。

因此,我不确定为什么编译器(尝试使用 gccclang)抱怨(带有警告,但有效)const T[][x],因为它不是 完全和上面一样。但是,总的来说,我可能会说这种问题会根据您的编译器以不同的方式解决(如gccclang),所以永远不要使用const T[][x]

在我看来,最好的选择是使用直接指针:

void imprimir_arreglo( const int *a, int nrows, int ncols )
{
  int i;  /*Contador filas*/
  int j;  /*Contador columnas*/

  for (i = 0; i < nrows; i++)
  {
    for (j = 0; j < ncols; j++)
    {
      printf( "%d ", *(a + i * ncols + j) );
    }

    printf( "\n" );
  }
}

然后调用:

imprimir_arreglo( arreglo1[0], 2, 3 );

这样,您的函数将更加动态和便携。

【讨论】:

  • 好的,谢谢你的回答,但我想知道为什么会出现这种行为??
  • @ChristianCisneros,我试图以肤浅的方式解释,但也许我做不到。尝试阅读关于 GCC 的 bugzilla herehere 的相同讨论。
  • 好的 @MatheusOI 谢谢你的精彩回答,我会阅读讨论。
【解决方案2】:

中删除 const
void imprimir_arreglo( const int a[2][3] );

void imprimir_arreglo( const int a[2][3] )
{

你的代码就可以工作了。

【讨论】:

  • 我知道@Armin,但我怀疑为什么这种行为只发生在矩阵而不是向量中?
  • @ChristianCisneros 据我所知 [c] 没有向量。如果你正在使用一个特殊的库,你应该提到它。
  • 据我所知,向量是一个只有一个子索引的数组,而矩阵是一个有多个子索引的数组
猜你喜欢
  • 2022-12-13
  • 2020-03-28
  • 2011-02-03
  • 2019-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
相关资源
最近更新 更多