簡體   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