嗨,
我对C的malloc函数有点新,但据我所知,它应该将值存储在堆中,因此您可以使用来自原始范围之外的指针来引用它.我创建了一个应该执行此操作的测试程序,但在运行程序后,我一直得到值0.我究竟做错了什么?
#include <stdio.h>
#include <stdlib.h>
int f1(int *b) {
b = malloc(sizeof(int));
*b = 5;
}
int main(void) {
int *a;
f1(a);
printf("%d\n", a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
raj*_*raj 26
是! a是按值传递的,因此b函数中的指针f1将是本地的..返回b,
int *f1() {
int * b = malloc(sizeof(int));
*b = 5;
return b;
}
int main() {
int * a;
a = f1();
printf("%d\n", *a);
// keep it clean :
free(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
或通过a的地址
int f1(int ** b) {
*b = malloc(sizeof(int));
**b = 5;
}
int main() {
int * a;
f1(&a);
printf("%d\n", *a);
// keep it clean :
free(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
看起来你误解了C的工作方式的基本部分 - 即它是一种'按值传递'的语言.为了main()了解您分配的内存,您必须将其恢复原状.以下代码将为您提供所需的代码:
int f1(int **b)
{
*b = malloc(sizeof(int));
**b = 5;
}
int main(int argc, char **argv)
{
int *a;
f1(&a);
printf("%d\n", *a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这段代码与你的代码有一些区别; 首先,签名f1()已经改变,以便它可以malloc()在传入的指针中返回调用的结果.接下来,调用f1()已被更改为传递地址a而不是a自身 - 重要的是,如果您希望它被"填写" f1(),可以这么说.最后,printf()in main()已被更改为打印出指向的值而不是指针本身.
内存本身仍然存在,但它会泄漏,因为您没有提供分配给调用者的指针.此外,您a应该在打印时进行打印*a.最后,你没有从中返回一个int f1.
尝试:
void f1(int **b) {
*b = malloc(sizeof(int));
**b = 5;
}
int main() {
int *a;
f1(&a);
printf("%d\n", *a);
free(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
让我们假设您NULL在调用函数之前为a 赋值f1.现在定义f1的方式,它int通过值获取其参数(指向a的指针).也就是说b将类型的另一变量int *,这将是一个复制的a.所以b也会有价值NULL.现在,f1您可以b通过为其分配动态分配的内存地址来更改值malloc.可以说内存地址是0x123.作为此赋值的结果,b已将其值更改NULL为0x123但是a(in main)继续保持NULL,因为更改b不会更改a,因为它们是两个单独的变量.因此,当您从函数返回时,f1a将保持不变.
有两种方法可以解决这个问题.您可以使函数f1返回已更改的值,b然后将其分配回in main和two,您可以传递a by地址,以便所做的任何更改f1也会影响in main.
// f1 now returns the value of b.
int* f1() {
int *b = malloc(sizeof(int));
*b = 5;
return b;
}
int main() {
int *a = NULL;
a = f1(); // assign the return value of f1 to a.
printf("%d\n", *a); // prints 5...not its *a not just a.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
.
// f1 now takes the address of a.
void f1(int **b) {
*b = malloc(sizeof(int)); // you are actually altering a indirectly.
**b = 5;
}
int main() {
int *a = NULL;
f1(&a); // now pass the address of a to f1.
printf("%d\n", *a); // prints 5...not its *a not just a.
return 0;
}
Run Code Online (Sandbox Code Playgroud)