首页 > 解决方案 > 使用 malloc 进行动态内存分配

问题描述

    # 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); 
}

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

标签: c++pointersmallocdynamic-memory-allocationdereference

解决方案


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

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

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

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


推荐阅读