繁体   English   中英

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

[英]Why i can't compile without declare a matrix like 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这样的矩阵变量的情况下进行编译,并且在向量中我可以...为什么会出现这种现象? 对不起,如果我的英语不好,我会说西班牙语。 非常感谢您的回答。

从中删除const

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

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

这样您的代码就会起作用。

这个问题真是一团糟。 您不应该将常量修饰符用于间接指针,例如const int** ,因为这样可能会造成混乱,例如:

  1. 不能修改值是否是int **

  2. 还是它是const int *的指针(甚至数组)?

在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 );

这样,您的功能将更加动态和可移植。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM