我正试图在我的办公桌上编译并运行leetcode的一个问题的答案,这1只是为了练习和学习而提出的,但当我试图在特定的代码行中运行时,就会出现双指针问题。
int **vale=(int**)malloc(n*sizeof(int*));
//*vale=(int*)malloc(m*sizeof(int*));
vale = spiralMatrix(m, n, Lista, ptr, vale);}
问题是当代码到达*returnColumnSizes行时,代码崩溃。我知道双指针就像一个矩阵,为了使用,我们需要分配内存,所以我首先分配双指针。所以现在我可以把它发送到函数,但它不起作用。我做错了什么?
int** spiralMatrix(int m, int n, struct ListNode* head, int* returnSize, int** returnColumnSizes){
*returnSize = m;
*returnColumnSizes = (int*)malloc(m*sizeof(int)); ---> this crash
int **res = (int**)malloc(m*sizeof(int*));
谢谢!
为了避免XY问题,我不会试图回答您的LeetCode问题。相反,我们将讨论您的主题的中心问题,">How can I Correct Pass this double pointer to a function in C";。
双指针只是指指向另一个指针的地址。例如,假设我们有一个简单的指针,char* foo = "Hello"
,如果我们把foo
传递给一个函数,我们会给出"Hello"
的地址,但如果我们想传递foo
本身,这里双指针的概念变得很方便,char** bar = &foo
,现在,如果我们传递bar
,我们这次传递的是foo
的地址,而不是"Hello"
。
完整示例:
#include <stdio.h>
void change_by_pointer(char* s) {
s = "One";
}
void change_by_double_pointer(char** s) {
*s = "Double";
}
int main() {
char* foo = "Hello";
printf("foo = %sn", foo);
// Change by pointer
change_by_pointer(foo);
printf("foo = %sn", foo);
// Change by double pointer
char** bar = &foo;
change_by_double_pointer(bar); // Or change_by_double_pointer(&foo);
printf("foo = %sn", foo);
return 0;
}
输出:
foo = Hello
foo = Hello
foo = Double
最后,我不确定你想用spiralMatrix()
做什么,但根据params数据类型,这就是你处理它的方式。
#include <stdio.h>
// Please ignore the behavior of this function.
// This is just an example of how you deal with double-pointers.
int** spiralMatrix(int m, int n, struct ListNode* head, int* returnSize, int** returnColumnSizes){
*returnSize = m;
*returnColumnSizes = malloc(m * sizeof(int));
**returnColumnSizes = 3;
int **res = returnColumnSizes;
return res;
}
int main() {
int returnSize = 1;
int* returnColumnSizes = NULL;
printf("returnSize = %dn", returnSize);
printf("Calling spiralMatrix()...n");
int** Res = spiralMatrix(2, 0, NULL, &returnSize, &returnColumnSizes);
printf("returnSize = %dn", returnSize);
printf("returnColumnSizes = %dn", *returnColumnSizes);
printf("Res = %dn", **Res);
return 0;
}
输出:
returnSize = 1
Calling spiralMatrix()...
returnSize = 2
returnColumnSizes = 3
Res = 3