我正在尝试访问在函数fooA()
main
函数中创建的array
。我使用malloc
动态分配array
并将传递的指针指向它,但主要指针不再指向相同的值。
int main() {
int *test;
fooA(test);
printf("%dn", test[0]);
free(test);
}
void fooA(int *pass){
int pass = malloc(5*sizeof(int));
for(int i=0;i<5;i++){
pass[i] = i;
}
}
首先,代码中的问题....
void fooA(int *pass) /*<<<< pass is declared here */
{
/*
however you have redefined pass as a different type here.
This variable hides the previous definition of pass.
I'd suggest turning up the warning level on your compiler
to catch errors like this. (-Wall on gcc/clang, or warning
level 4 on Visual C)
*/
int pass = malloc(5*sizeof(int));
for(int i=0;i<5;i++){
pass[i] = i;
}
}
稍后调用该方法时,您将测试的副本传递到 fooA 中,而不是对原始变量的引用。 即您在 fooA 中对"pass"所做的任何更改都将处理副本,而不是原始变量。
int *test;
fooA(test);
这里最简单的选择是简单地返回指针。
/* change the prototype to return the pointer instead of passing in as arg! */
int* fooA(void);
int main() {
/* this should now be good */
int *test = fooA();
printf("%dn", test[0]);
free(test);
}
int* fooA(void){
int* pass = malloc(5*sizeof(int));
for(int i=0;i<5;i++){
pass[i] = i;
}
return pass;
}
如果你想用函数参数来做到这一点,这是可能的,但前提是你使用指向指针的指针,即
void fooA(int** pass);
int main() {
int *test;
fooA(&test); /*< passing address of test variable */
printf("%dn", test[0]);
free(test);
}
void fooA(int** pass) {
/* need to dereference pass here to modify the original pointer value */
*pass = malloc(5*sizeof(int));
for(int i=0;i<5;i++){
(*pass)[i] = i;
}
}
虽然这个问题被标记为 C,但为了完整起见,C++您可以通过引用传递变量(即将 & 符号添加到类型的末尾(
void fooA(int*& pass) {
// working on the original variable, rather than a copy.
pass = (int*)malloc(5*sizeof(int));
for(int i=0;i<5;i++){
pass[i] = i;
}
}
现在这段代码可以正常工作:
int *test;
fooA(test);