[英]Why can't my dynamically allocated array be accessed outside of it's function? [C]
我正在尝试访问在main
函数的fooA()
函数中创建的array
。 我正在使用malloc
动态分配array
并将传递的指针指向它,但在 main 中,指针不再指向相同的值。
int main() {
int *test;
fooA(test);
printf("%d\n", 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;
}
}
稍后当您调用该方法时,您将test 的副本传递到 fooA,而不是对原始变量的引用。 即,您在 fooA 中对“传递”所做的任何更改都将作用于副本,而不是原始变量。
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("%d\n", 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("%d\n", 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.