c - 带有 malloc 的指针无法在函数中存活
问题描述
我是一个 C 初学者,我不明白为什么我在这里遇到错误。我被告知指针可以在带有 的函数中存活malloc
,但在这里我得到了code dumped
.
我需要得到这个并且在互联网上找不到任何东西。我知道你可以做到完全不同,但我不想使用全局变量或指向指针的指针。我很想了解malloc
!
#include <stdio.h>
#include <stdlib.h>
void doStuff();
void doStuff(int *a) {
a = malloc(sizeof(int));
*a = 3;
printf("%d \n", *a);
};
int main() {
int *a;
doStuff(a);
printf("%d", *a);
free(a);
}
解决方案
你掉进了经典的 c 函数参数陷阱。阅读本文以了解 c 中的“按值传递”。阅读并理解该链接中的所有内容非常重要,但简单的版本是您分配给的值a
不会在函数之外存在。重要的是要注意在这里使用 malloc 是无关紧要的,这是你传递导致问题的参数的方式。
您在评论中包含的参考资料显示了您将如何在 malloc 部分中正确执行此操作:
#include <stdlib.h>
/* allocate and return a new integer array with n elements */
/* calls abort() if there isn't enough space */
int *
makeIntArray(int n)
{
int *a;
a = malloc(sizeof(int) * n);
if(a == 0) abort(); /* die on failure */
return a;
}
但是,如果您不需要使用malloc
,则创建一个 int,传递 int 的地址,然后直接在函数中更改它,如下所示:
#include <stdio.h>
#include <stdlib.h>
void doStuff();
void doStuff(int *a){
*a = 3;
printf("%d \n", *a);
};
int main(){
int a;
doStuff(&a);
printf("%d", a);
}
推荐阅读
- reactjs - 带有 React 和 Docker 的 ASP.Net Core 2.2 或 3.1 SPA
- python - Flask and Pytest - PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
- cmake - Cmake support for tasking tri-core compiler toolchain
- python - Xarray 按多次运行和时间分组
- three.js - Showing Point Cloud Structure using Lighting in Three.js
- aws-lambda - Can AWS Lambda be used as the backend for getstream.io?
- powershell - 错误计数和 $Error 自动变量不一致
- quarkus - 构建 graalvm 可执行文件时是否有用于 H:+TraceClassInitialization 的 pom.xml 选项?
- javascript - How to get the date value from DaterRangePicker?
- r - Organize numbers in group ascending