【问题标题】:Double and triple pointers in CC中的双指针和三指针
【发布时间】:2014-02-25 00:36:59
【问题描述】:

我有一个如下所示的小程序。这个程序是为了更好地理解'C'中的指针变量是如何在内存中排列的。

#include <stdio.h>

const char *c = "hello";
const char **cp = &c;
const char ***cpp = &cp;
const char ****cppp = &cpp;

int main()
{

    printf("PTR (c)       : %p \n",c);
    printf("PTR (cp)      : %p \n",cp);
    printf("PTR (cpp)     : %p \n",cpp);
    printf("PTR (cppp)    : %p \n",cppp);
    printf("CONTENT (c)   : %c \n",*c);
    printf("CONTENT (cp)  : 0x%x \n",*(unsigned int*)cp);
    printf("CONTENT (cpp) : 0x%x \n",*(unsigned int*)cpp);
    printf("CONTENT (cppp): 0x%x \n",*(unsigned int*)cppp);
    return 0;
}

我在 PC (Ubuntu 12.04) x86_64 上得到的输出如下

PTR (c)       : 0x4006dc 
PTR (cp)      : 0x601020 
PTR (cpp)     : 0x601028 
PTR (cppp)    : 0x601030 
CONTENT (c)   : h 
CONTENT (cp)  : 0x4006dc 
CONTENT (cpp) : 0x601020 
CONTENT (cppp): 0x601028 

输出看起来不错,因为

  • cp包含c的地址
  • cpp包含cp的地址
  • cppp包含cpp的地址

现在我对上述程序的二进制可执行文件进行 nm 处理。

0000000000600e50 d _DYNAMIC
0000000000600fe8 d _GLOBAL_OFFSET_TABLE_
00000000004006d8 R _IO_stdin_used
                 w _Jv_RegisterClasses
0000000000600e30 d __CTOR_END__
0000000000600e28 d __CTOR_LIST__
0000000000600e40 D __DTOR_END__
0000000000600e38 d __DTOR_LIST__
0000000000400860 r __FRAME_END__
0000000000600e48 d __JCR_END__
0000000000600e48 d __JCR_LIST__
0000000000601040 A __bss_start
0000000000601010 D __data_start
0000000000400690 t __do_global_ctors_aux
0000000000400460 t __do_global_dtors_aux
0000000000601018 D __dso_handle
                 w __gmon_start__
0000000000600e24 d __init_array_end
0000000000600e24 d __init_array_start
0000000000400680 T __libc_csu_fini
00000000004005f0 T __libc_csu_init
                 U __libc_start_main@@GLIBC_2.2.5
0000000000601040 A _edata
0000000000601050 A _end
00000000004006c8 T _fini
00000000004003c8 T _init
0000000000400410 T _start
0000000000601020 D c
000000000040043c t call_gmon_start
0000000000601040 b completed.6531
0000000000601028 D cp
0000000000601030 D cpp
0000000000601038 D cppp
0000000000601010 W data_start
0000000000601048 b dtor_idx.6533
00000000004004d0 t frame_dummy
00000000004004f4 T main
                 U printf@@GLIBC_2.2.5

下面我已经重述了相关的内容。

0000000000601020 D c
0000000000601028 D cp
0000000000601030 D cpp
0000000000601038 D cppp

据我所知,解释如下。

'c'是数据段的一部分(用'D'表示)并且在地址0000000000601020 根据我的程序是'cp'的地址。这是所有变量的情况。

我在这里遗漏了什么重要的东西吗?这是初学者试图很好地理解 C 指针。

【问题讨论】:

  • 是的,实际上给定的位置是指针。

标签: c pointers memory-management pointer-to-pointer


【解决方案1】:

'c'是数据段的一部分(用'D'表示)并且在地址0000000000601020根据我的程序是'cp'的地址。

实际上,当您打印时:

printf("PTR (cp)      : %p \n",cp);

这是cp,而不是cp地址cp正是c地址,因为cp 是一个指向c 的指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    相关资源
    最近更新 更多