Chinaunix首页 | 论坛 | 博客
  • 博客访问: 150851
  • 博文数量: 28
  • 博客积分: 1476
  • 博客等级: 上尉
  • 技术积分: 356
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-11 11:39
文章分类
文章存档

2011年(1)

2010年(18)

2009年(9)

我的朋友

分类: 嵌入式

2009-11-24 17:18:09

    这次我们将举个例子说明指针是怎么被函数调用的,请看如下代码:      

//hello.c

#include

char *code = "code";

void fun1(char **name)
{
    char *hello = "hello";
    char *hello1 = "world";
    *name = hello;
}

void fun2(char *name)
{
    char *test = "test";
    name = test;
}


int main()
{
    char *name = "Lu xi";
    fun1(&name);
    fun2(name);
    return 0;
}

下面看看调试的过程:


lcw@pointer_test>>> gdb ./a.out
GNU gdb 6.8
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i586-suse-linux"...
(gdb) b 19
Breakpoint 1 at 0x80483d7: file hello.c, line 19.
(gdb) r
Starting program: /home/lcw/embedded/test_code/pointer_test/a.out

Breakpoint 1, main () at hello.c:20
20 {
(gdb) s
main () at hello.c:21
21 char *name = "Lu xi";
(gdb) s
22 fun1(&name);
(gdb) p &name
$1 = (char **) 0xbfa9b850
(gdb) p name
$2 = 0x80484f6 "Lu xi"
(gdb) p *name
$3 = 76 'L'
(gdb) x/w 0xbfa9b850
0xbfa9b850: 0x080484f6

//由上可以看出指针的地址,字符串的地址,接下来要进入到函数中了
(gdb) s
fun1 (name=0xbfa9b850) at hello.c:7
7 char *hello = "hello";

//可看出我们传递的是指针name的地址0xbfa9b850,这时为了要保存这个地址我们要重新创建一个指针来保存这个指针的地址


(gdb) p &name
$4 = (char ***) 0xbfa9b840
(gdb) x/w 0xbfa9b840
0xbfa9b840: 0xbfa9b850

//现在我们看到了保存0xbfa9b850这个地址的指针的地址是0xbfa9840,这是一个三级的指针,我们一层一层的往下看    

(gdb) p name
$5 = (char **) 0xbfa9b850
(gdb) p *name
$6 = 0x80484f6 "Lu xi"
(gdb) p **name
$7 = 76 'L'

//让我们来看看各级指针加1以是个什么值

(gdb) p **(name+1)
$8 = 1 '\001'     //这是指针的下一个指针,因为为空,所以值是错的
(gdb) p **name+1
$9 = 77     //这个77实际上就是76+1后的值,而76是'L'的ASCII码
(gdb) p **name
$10 = 76 'L'
(gdb) p *(*name+1)

$11 = 117 'u'  //这是指针所指向的字符的地址的下一个字符
(gdb) p **name+1
$12 = 77
(gdb) p/x *(*name+1)
$13 = 0x75
(gdb) s
8 char *hello1 = "world";
(gdb) s
9 *name = hello;
(gdb) p *name
$14 = 0x80484f6 "Lu xi"
(gdb) p hello
$15 = 0x80484e5 "hello"
(gdb) s
10 }
(gdb) s
main () at hello.c:23

//进入下一个函数,注意上面指针内容的变化
fun2 (name=0x80484e5 "hello") at hello.c:14
14 char *test = "test";

//这里主函数里定义的指针name,它所指向的内容发生了变化
(gdb) p &name
$16 = (char **) 0xbfa9b840
(gdb) p name
$17 = 0x80484e5 "hello"
(gdb) p *name
$18 = 104 'h'

//这里注意这个函数中的的指针与上一个函数中的变化,上一个是个2级指针**name,这里是个一级指针*name。
(gdb) s
15 name = test;
(gdb) s
16 }
(gdb) s
main () at hello.c:24
24 return 0;

(gdb) s
25 }

//这里与上一个函数中指针的赋值方法有所不同,但是归根结底指针的地址从一定义的时候就已经确定了,并且不能改变;而指针里的的内容是可以修改的。   

    关于指针的理解基本上就算完了,总结起来也就几点:1,指针是什么样的;2,指针是怎么传递的;而指针的传递无非有两总:1,传值,这种方法是将指针拟指向的值传递给函数使用,若函数中修改这个值对指针原来所指向的值是没有影响的,也就是说,指针返回后值不变;2,传地址,若以地址的形式将指针的地址传给函数,在函数中对这个地址所指向的值进行修改,在函数返回后指针所指向的值也会相应的被修改。最后一个问题了,指向指针的指针,这个问题留到下一次在做解释。

阅读(1348) | 评论(0) | 转发(0) |
0

上一篇:指针的理解1

下一篇:函数指针和指针函数

给主人留下些什么吧!~~