指针传参及分配空间

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>

using namespace std;

void GetCharMemory(char **p, int num)
{
    *p = (char*)malloc(sizeof(char) * num);
}

int main(void)
{
    char *str = NULL;
    GetCharMemory(&str, 100);
    strcpy(str, "hello");
    cout<<str<<endl;
    free(str);
}


依次分析:

第一句 char *str = NULL; 定义字符指针str ,且str自身地址为:0x7fffffffe1d8,值为0x0。 

(gdb) p &str
$1 = (char **) 0x7fffffffe1d8
(gdb) p str
$2 = 0x0

第二句 GetCharMemory(&str, 100); 将指针的地址和分配空间的大小传进去。

然后进入方法 GetCharMemory 中,此时形参char **p本身的地址为:0x7fffffffe1b8,p 的值等于传进来str的地址0x7fffffffe1d8,即p指向str。

p所指向的地址0x7fffffffe1d8的值即*p也是指针str的值仍为0x0。

(gdb) p &p
$3 = (char ***) 0x7fffffffe1b8
(gdb) p p
$4 = (char **) 0x7fffffffe1d8
(gdb) p *p
$5 = 0x0

然后这句 *p = (char*)malloc(sizeof(char) * num); 是给p所指向的str分配值。这个值是一块100个char类型大小的连续空间的首地址。再看此时*p的值:

(gdb) p *p
$6 = 0x602010 ""

分配空间后接下来给str指向的空间赋值 strcpy(str, "hello");,此时再看该地址的值:

(gdb) p &str
$7 = (char **) 0x7fffffffe1d8
(gdb) p str 
$8 = 0x602010 "hello"
(gdb) p str+1
$9 = 0x602011 "ello"

 上面可以看出指针str的值等于 GetCharMemory 方法分配的值,并且在str所指向地址(即str的值)对应的空间可以写入数据,同时该地址(0x602010)是分配后连续空间的首地址。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值