use*_*058 33 c arrays pointers
我正在学习C并且无法将2D数组的指针传递给另一个函数然后打印2D数组.任何帮助,将不胜感激.
int main( void ){
char array[50][50];
int SIZE;
...call function to fill array... this part works.
printarray( array, SIZE );
}
void printarray( char **array, int SIZE ){
int i;
int j;
for( j = 0; j < SIZE; j++ ){
for( i = 0; i < SIZE; i ++){
printf( "%c ", array[j][i] );
}
printf( "\n" );
}
}
Run Code Online (Sandbox Code Playgroud)
Car*_*rum 27
char **
不代表2D数组 - 它将是一个指向指针的数组.printarray
如果要将其传递给2D数组,则需要更改定义:
void printarray( char (*array)[50], int SIZE )
Run Code Online (Sandbox Code Playgroud)
或等效地:
void printarray( char array[][50], int SIZE )
Run Code Online (Sandbox Code Playgroud)
在main()中,变量"array"声明为
char array[50][50];
Run Code Online (Sandbox Code Playgroud)
这是一个2500字节的数据.传递main()的"数组"时,它是指向该数据开头的指针.它是指向预期以50行组织的char的指针.
然而在函数printarray()中,您声明了
char **array
Run Code Online (Sandbox Code Playgroud)
"array"这里是指向"char*指针"的指针.
@Lucus建议"void printarray(char array [] [50],int SIZE)"工作,但它不是通用的,因为你的SIZE参数必须是50.
想法:打败(yeech)printarray()中参数数组的类型
void printarray(void *array, int SIZE ){
int i;
int j;
char *charArray = (char *) array;
for( j = 0; j < SIZE; j++ ){
for( i = 0; i < SIZE; i ++){
printf( "%c ", charArray[j*SIZE + i] );
}
printf( "\n" );
}
}
Run Code Online (Sandbox Code Playgroud)
更优雅的解决方案是使main()中的"数组"成为指针数组.
// Your original printarray()
void printarray(char **array, int SIZE ){
int i;
int j;
for( j = 0; j < SIZE; j++ ){
for( i = 0; i < SIZE; i ++){
printf( "%c ", array[j][i] );
}
printf( "\n" );
}
}
// main()
char **array;
int SIZE;
// Initialization of SIZE is not shown, but let's assume SIZE = 50;
// Allocate table
array = (char **) malloc(SIZE * sizeof(char*));
// Note: alternative syntax
// array = (char **) malloc(SIZE * sizeof(*array));
// Allocate rows
for (int row = 0; row<SIZE; row++) {
// Note: sizeof(char) is 1. (@Carl Norum)
// Shown here to help show difference between this malloc() and the above one.
array[row] = (char *) malloc(SIZE * sizeof(char));
// Note: alternative syntax
// array[row] = (char *) malloc(SIZE * sizeof(**array));
}
// Initialize each element.
for (int row = 0; row<SIZE; row++) {
for (int col = 0; col<SIZE; col++) {
array[row][col] = 'a'; // or whatever value you want
}
}
// Print it
printarray(array, SIZE);
...
Run Code Online (Sandbox Code Playgroud)
小智 5
由于 C99 支持动态大小的数组,因此以下样式更方便地传递 2 维数组:
void printarray( void *array0, int SIZE ){
char (*array)[SIZE] = array0;
int i;
int j;
for( j = 0; j < SIZE; j++ ){
for( i = 0; i < SIZE; i ++){
printf( "%c ", array[j][i] );
}
printf( "\n" );
}
}
Run Code Online (Sandbox Code Playgroud)