[英]*expected 'int *' but argument is of type 'int **'* warning in c
[英]expected ‘int **’ but argument is of type ‘int (*)[3]’
我剛剛開始修改多維數組中的指針,並試圖將數組傳遞給 void 函數。 編譯器只是拋出了一個錯誤。 我需要將數組完全作為指針傳遞,然后通過引用更改它。
#include <stdio.h>
#include <stdlib.h>
void Func(int** matrix, int sizeFirst, int sizeSecond)
{
for (int i = 0; i < sizeFirst; i++)
{
for (int j = 0; j < sizeSecond; j++)
{
printf("%d\n", matrix[i][j]);
}
}
}
int main()
{
int array[2][3] = {
{5,8,2},
{1,3,6}
};
int sizeMain = sizeof(array)/sizeof(array[0]);
int sizeInner = sizeof(array[0])/sizeof(array[0][0]);
Func(array, sizeMain, sizeInner);
return 0;
}
二維數組不是指向指針的指針。 您的代碼無效,因為 Func 不知道每行有多少列。 此外,使用正確的大小和索引類型
void Func(size_t sizeFirst, size_t sizeSecond, int (*matrix)[sizeSecond])
{
for (int i = 0; i < sizeFirst; i++)
{
for (int j = 0; j < sizeSecond; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main()
{
int array[2][3] = {
{5,8,2},
{1,3,6}
};
size_t sizeMain = sizeof(array)/sizeof(array[0]);
size_t sizeInner = sizeof(array[0])/sizeof(array[0][0]);
Func(sizeMain, sizeInner, array);
return 0;
}
首先你要明白int **
代表什么,它代表指向整型指針的指針,舉個例子:
int a = 10;
int *p = &a; // 'p' points to 'a`
int **pp = &p; // 'pp' points to 'p' (pointer to integer)
因此,您不能將int **
用於整數數組。 現在已經不礙事了,讓我們看看你能做些什么(解決方案)
您可以簡單地在這樣的函數定義中添加指向整數數組的指針
void Func(int *matrix[], int rows, int cols)
或者你可以簡單地做
void Func(int matrix[rows][cols])
注意:字符串數組或二維字符數組( char array[][]
)可以表示為char**
使用指向 VLA 的指針,您可以保留參數類型中的所有維度,然后讓 C 為您進行多維縮放。
在舊版本的 C 中,您需要手動計算點,記住從右邊開始的第一個維度移動 1(按 sizeof(type) 縮放,C 為您做的),第二個從右邊開始的第一個維度,第三個右邊的第一個維度乘以右邊的第二個維度,依此類推。
它有點像數字中的數字(單位、十、百……),只是下一個縮放比例是前一個縮放比例乘以前一個維度而不是一個常數基數。 (您可以讓 C 通過減去一些&decdigits[a][b][c]
和&decdigits[0][0][0]
來將十進制數字組轉換為十進制數字,其中decdigits
是一些decdigits[10][10][10]
, 即: char decdigits[10][10][10]; printf("%d\\n", (int)(&decdigits[1][2][3] - &decdigits[0][0][0])) /*prints 123*/;
)
#include <stdio.h>
void Func( int sizeFirst, int sizeSecond, int (*matrix)[sizeFirst][sizeSecond])
{
for (int i = 0; i < sizeof((*matrix))/sizeof((*matrix)[0]) ; i++)
{
for (int j = 0; j < sizeof((*matrix)[0])/sizeof((*matrix)[0][0]) ; j++)
{
printf("%d ", (*matrix)[i][j]);
}
puts("");
}
}
void Func_89( int sizeFirst, int sizeSecond, int *matrix)
{
for (int i = 0; i < sizeFirst; i++)
{
for (int j = 0; j < sizeSecond; j++)
{
printf("%d ", matrix[i*sizeSecond + j]);
}
puts("");
}
}
int main()
{
int array[2][3] = {
{5,8,2},
{1,3,6}
};
int sizeMain = sizeof(array)/sizeof(array[0]);
int sizeInner = sizeof(array[0])/sizeof(array[0][0]);
Func(sizeMain, sizeInner,&array );
puts("===");
Func_89(sizeMain, sizeInner,&array[0][0] );
//char decdigits[10][10][10]; printf("%d\n", (int)(&decdigits[1][2][3] - &decdigits[0][0][0])); //123
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.