[英]1D array being treated as 2D array in function - C
Please tell me if the title is not entirely correct.如果标题不完全正确,请告诉我。
I first initialize a pointer to array using malloc in the main, then I pass it to a function which receives a pointer to pointer to int like this:我首先在 main 中使用 malloc 初始化一个指向数组的指针,然后将它传递给一个函数,该函数接收一个指向 int 的指针的指针,如下所示:
void readfile(int**);
int main(void)
{
int (*obsF) = malloc(sizeof(int)*16);
readfile(&obsF);
free(obsF);
}
void readfile(int **obsF)
{
//I can do this without errors:
obsF[0][1] = 1;
}
I don't understand why I have to treat it as a 2D array, because if I do obsF[1] = 1
I get an error.我不明白为什么我必须把它当作一个二维数组,因为如果我做obsF[1] = 1
我会得到一个错误。 Could someone explain me why this happens?有人能解释一下为什么会发生这种情况吗?
Change your function signature from void readfile(int**)
to void readfile(int*)
and from void readfile(int **obsF)
to void readfile(int *obsF)
.将您的函数签名从void readfile(int**)
更改为void readfile(int*)
并将void readfile(int **obsF)
更改为void readfile(int *obsF)
。
When you put the function signature as int**, the compiler treats it as a pointer to a pointer, and thus it is treated as a 2D array, and not a 1D array.当您将函数签名设为 int** 时,编译器将其视为指向指针的指针,因此将其视为二维数组,而不是一维数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.