您的位置:首页 > 编程语言 > C语言/C++

C/C++ 内存传递 指针

2015-12-19 17:41 357 查看
程序1:

[cpp] view
plaincopy

void getmemory(char *p)

{

p=(char*)malloc(100);

}

void test(void)

{

char * str = NULL;

getmemory(str);

strcpy(str,"hello,world");

printf(str);

}



int main()

{

test();

}

程序1运行是会报错的,调用getmemory(str)后,在test函数内的局部变量str并未产生变化, strcpy ( str ,” hello , world ”) 写越界,造成segmentation
fault。

要修改以上程序有两个办法,

修改1: 形参由char *p改成char *&p就正确了

[cpp] view
plaincopy

void getmemory(char *&p)

{

p=(char*)malloc(100);

}

void test(void)

{

char * str = NULL;

getmemory(str);

strcpy(str,"hello,world");

printf(str);

}



int main()

{

test();

}

修改2:传入str的地址,形参改为指向指针的指针

[cpp] view
plaincopy

void getmemory(char **p)

{

*p=(char*)malloc(100);

}

void test(void)

{

char * str = NULL;

getmemory(&str);

strcpy(str,"hello,world");

printf(str);

}



int main()

{

test();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: