简体   繁体   English

指向char的指针的地址与指向char的指针的指针之间的区别

[英]difference between address of pointer to char and pointer to pointer to char

I have following sample of code: 我有以下代码示例:

#include <stdio.h>

int main(void)
{
   char *text[2];
   text[0] = "Hello";
   text[1] = "World";

   printf("Address of text[0]: %p\n", text[0]);
   printf("Address of text   : %p\n", text);

   return 0;
}

The output of this program is: 该程序的输出是:

Address of text[0]: 0x400694
Address of text   : 0x7ffcac41b000

I am wondering why these addresses differ in length. 我想知道为什么这些地址的长度不同。 Why is address of first pointer to char only 6 digits length? 为什么第一个指向char的地址只有6位数?

There is no difference in "address length", the difference is in the value . “地址长度”没有区别,差异在于

In this particular case, I assume the text[0] pointer points to a data segment that holds the compile time value "Hello" , and the text pointer points to a runtime address. 在这种特殊情况下,我假设text[0]指针指向保存编译时间值"Hello"的数据段, text指针指向运行时地址。

Since these are at different memory segments, they can be "very far" and so you get the output you see. 由于它们位于不同的内存段,因此它们可以“非常远”,因此您可以获得所看到的输出。

The first address is the address of "Hello", which is stored in your data segment. 第一个地址是“Hello”的地址,它存储在您的数据段中。

The second address is the address of text[] , which is stored in your stack. 第二个地址是text[]的地址,它存储在堆栈中。

These two areas of memory are far from each other, so one has many digits, the other has few digits. 这两个内存区域彼此相距很远,因此一个有多个数字,另一个有几个数字。

Apparently, %p renders only as many digits as necessary to represent the address. 显然, %p只渲染表示地址所需的数字。

printf("Address of text[0]: %p\n", text[0]);

prints the address of C string (the address first element of array points to), while: 打印C字符串的地址(数组指向的地址第一个元素),同时:

printf("Address of text   : %p\n", text);

prints the address of array's first element. 打印数组第一个元素的地址。

To get the address of the first item of the array text , you'll have to use: 要获取数组text的第一项的地址,您必须使用:

printf("Address of text[0]: %p\n", (void *)&text[0]);

In your question, you are printing the address of the first character of the string "Hello" (in other words, of the content of text[0]), not the address of the first element of the array text , ie not the address of text[0] , just the address stored in text[0] . 在您的问题中,您正在打印字符串"Hello"的第一个字符的地址(换句话说,是文本[0]的内容 ),而不是数组text的第一个元素的地址,即不是地址 text[0]只存储地址text[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM