2013-02-20 99 views
2

我无疑是一个矩阵是:为什么在这个代码:我为什么不能编译不声明类似于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*/ 

我不能编译不宣而像常量的矩阵变量,并在一个向量我可以...为什么会发生这种行为?对不起,如果我的英语不好,我说西班牙语。我会非常感谢你的回答。从

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

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

和你的代码

+0

什么?你的意思是函数参数?我认为你可以,错误是什么? – MatheusOl 2013-02-20 16:36:38

+0

我的编译器告诉我,我必须修改数组的类型,但这种行为只发生在矩阵,而不是在向量中,我想知道为什么? – 2013-02-20 19:24:37

回答

0

这个问题有一个真正的混乱。你不应该使用恒定的改性剂间接指针,如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); 

这样,你的功能更具活力,更加便于携带。

+0

好的谢谢你的答案,但我想知道为什么会发生这种行为? – 2013-02-21 04:51:12

+0

@ChristianCisneros,我试图用肤浅的方式解释,但也许我不能。尝试阅读关于GCC的bugzilla [here](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=20230)和[here](http://gcc.gnu.org/bugzilla/)的相同讨论show_bug.cgi?ID = 16895)。 – MatheusOl 2013-02-21 11:49:38

+0

好的@MatheusOI谢谢你的出色答案,我会阅读讨论。 – 2013-02-21 15:28:06

0

删除常量将正常工作。

+0

我知道@Armin,但我的疑惑是为什么这种行为只发生在矩阵中,而不是在向量中? – 2013-02-20 19:23:01

+0

@ChristianCisneros据我所知[c]没有矢量。如果你使用一个特殊的图书馆,你应该提及它。 – 2013-02-20 20:22:36

+0

向量是一个只有一个子索引的数组,矩阵是多个子索引的数组,据我所知 – 2013-02-21 04:49:43

相关问题