To avoid the XY Problem, I won't try to answer your LeetCode question. Instead, we will discuss your topic's central question, "How can I Correctly Pass this double pointer to a function in C".
Double pointer means simply an address that point to another pointer. For example, let's say we have a simple pointer, char* foo = "Hello"
, if we pass foo
to a function, we are giving the address of "Hello"
, But what if we want to pass foo
itself, here the concept of the double-pointer becomes handy, char** bar = &foo
, now, if we pass bar
, we are passing the address of foo
and not "Hello"
this time.
Full Example:
#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 = %s\n", foo);
// Change by pointer
change_by_pointer(foo);
printf("foo = %s\n", foo);
// Change by double pointer
char** bar = &foo;
change_by_double_pointer(bar); // Or change_by_double_pointer(&foo);
printf("foo = %s\n", foo);
return 0;
}
Output:
foo = Hello
foo = Hello
foo = Double
Finally, I'm not sure what you are trying to do with spiralMatrix()
but based on the params datatypes, this is how you deal with it.
#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 = %d\n", returnSize);
printf("Calling spiralMatrix()...\n");
int** Res = spiralMatrix(2, 0, NULL, &returnSize, &returnColumnSizes);
printf("returnSize = %d\n", returnSize);
printf("returnColumnSizes = %d\n", *returnColumnSizes);
printf("Res = %d\n", **Res);
return 0;
}
Output:
returnSize = 1
Calling spiralMatrix()...
returnSize = 2
returnColumnSizes = 3
Res = 3