gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:10 25 4
gpt4 key购买 nike

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

/*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 这样的矩阵变量,我就无法编译,而在 vector 中我可以……为什么会出现这种行为?对不起,如果我的英语不好,我会说西类牙语。非常感谢您的回答。

最佳答案

这个主题真的很乱。您不应该对间接指针使用常量修饰符,例如 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 运行时有警告但不会更改值(value)。

因此,我不确定为什么编译器(尝试使用 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 );

这样,您的函数将更加动态且可移植。

关于c - 为什么我不能在不声明像 const 这样的矩阵的情况下进行编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14985030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com