c++ - 使用 malloc 进行动态内存分配

标签 c++ pointers malloc dynamic-memory-allocation dereference

    # include<stdio.h> 
# include<stdlib.h> 
   
void fun(int *a) 
{ 
    a = (int*)malloc(sizeof(int)); 
} 
   
int main() 
{ 
    int *p; 
    fun(p); 
    *p = 6; 
    printf("%d\n",*p); 
    return(0); 
}

为什么上面的代码无效?为什么会出现段错误?

最佳答案

因为a本身是按值传递的,所以函数中对其自身的任何修改都与参数无关。

您可以将其更改为按引用传递

void fun(int *&a) 
{ 
    a = (int*)malloc(sizeof(int)); 
} 

顺便说一句:在 C++ 中,最好使用 new (和 delete),或者从一开始就不要使用原始指针。

关于c++ - 使用 malloc 进行动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63048903/

相关文章:

c - 如何使用指针访问递归结构

c++ - 当函数是指向类函数的指针但在该类之外时如何正确调用函数

c - 什么是用于嵌入式系统的良好 C 内存分配器?

c++ - 库中的函数名称已更改

c++ - GCC 链接静态库

c++ - getline 中的 "Invalid conversion"错误

通过在 C 中打印指针数组中的字符串元素来转换错误

c - 简单的 c malloc

Linux 内核 rb 树

c++ - 在STL映射中通过引用查找并返回