c - 为什么我的动态分配的数组不能在它的函数之外被访问?[C]
问题描述
我正在尝试访问array
在函数fooA()
中创建的main
函数。我正在动态分配array
使用malloc
并指向它的传递指针,但主要指针不再指向相同的值。
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);
推荐阅读
- c++ - 如何将 GNUstep 编译器添加到 Qt 创建者以让他们在 Windows 上编译 .mm 文件?
- javascript - 如何为 woocommerce_after_shop_loop_item 添加倒计时
- flask - Flask Admin - 有没有办法存储表格视图的当前 url(应用了自定义过滤器)?
- java - 编写 foreach 语句过滤 Binance API 结果返回任意数据
- r - 如何根据某些特殊字符将 data.frame 划分为多个 data.frames?
- android-lifecycle - Android MediatorLiveData 将多个 LiveData 结果组合成单个 LiveData 对象(在 Java 中)
- spring-boot - 如何使用graphql映射具有父类的java类作为字段
- mongodb - Mongoose find() 不返回所有字段(不可枚举)
- python - 在python中动态添加.kv childwidgets
- firebase - 与 .limitToLast 一起用于分页时,如何仅使用 .onSnapshot 从 firebase 获取新文档