将char指针作为函数参数出现的错误

错误的产生

最近在写数据结构关于串的各种操作的时候出了一点问题,就是把char指针作为函数参数,因为字符数组容量不够大,需要在函数中进行了重新分配空间,但是回到main函数中却并没有输出,后来思索发现是因为指针变量也是一个变量,他作为参数传入的时候也是传数值的,而不会吧指针变量本身的地址给传进去,有点类似于经典的swap()函数。
##试验

#include<cstdlib>
#include<cstdio>
void function(char* s);
int main(int argc,char** argv){
    char* s=(char*)malloc(10*sizeof(char));
    printf("main--------&s:%p\n",&s);
    printf("main--------s:%p\n",s);
    function(s);
}
void function(char* s){
    printf("fun--------&s:%p\n",&s);
    printf("fun--------s:%p\n",s);
    realloc(s,15*sizeof(char));
    printf("fun------realloc--------&s:%p\n",&s);
    printf("fun---realloc-----------s:%p\n",s);
}

结果是
结果
然后会发现main 和 fun中的s的地址发生了变化,但是s本身的数值并没有发生变化,说明分析是正确的。
同时realloc()函数的使用也就不能改变s在main中没有输出的结果。

改进

目前想到的办法就只有两个

  • 首先是第一:可以把函数的返回类型从void改为char*,这样只需要改变main中s的地址就可以了。
  • 第二个是使用引用,以前没有用过引用指针类型,但是现在试验了一下是可以的。代码改进如下:
#include<cstdlib>
#include<cstdio>
void function(char* &s);
int main(int argc,char** argv){
    char* s=(char*)malloc(10*sizeof(char));
    printf("main--------&s:%p\n",&s);
    printf("main--------s:%p\n",s);
    function(s);
}
void function(char* &s){
    printf("fun--------&s:%p\n",&s);
    printf("fun--------s:%p\n",s);
    realloc(s,15*sizeof(char));
    printf("fun------realloc--------&s:%p\n",&s);
    printf("fun---realloc-----------s:%p\n",s);
}

结果如下:
在这里插入图片描述

可以看到无论是指针的地址还是指针变量储存的值都一样了。

对于指针还有很多的问题,初次写博客并不完善,有更好的办法欢迎讨论~~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值