为什么我不能在不声明像const的矩阵的情况下编译

时间:2013-02-20 16:33:06

标签: c vector matrix const

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

/*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那样的矩阵变量,我就无法编译,而在向量中我可以...为什么会出现这种情况?对不起,如果我的英语不好,我会讲西班牙语。我非常感谢你的回答。

2 个答案:

答案 0 :(得分:0)

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

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

您的代码将有效。

答案 1 :(得分:0)

这个话题真是一团糟。您不应该使用常量修饰符来表示间接指针,例如const int**,因为可能会出现混乱,例如:

  1. int **值是否无法修改?

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

  3. 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 );
    

    这样,您的功能更具动态性和便携性。