为const char ** A = {"字符串1","字符串2"}和指针arithametic [英] const char **a = {"string1","string2"} and pointer arithametic

查看:210
本文介绍了为const char ** A = {"字符串1","字符串2"}和指针arithametic的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

main()
 {
     const char **a = {"string1","string2"};
     printf("%c", *a); /* prints s */
     printf("%s", a);  /* prints string1 */
     printf("%s", a+1);/* prints ng1 */
 }

GCC v4.8.3打印%s代表最后的printf,那里的的http:// codePAD .ORG / 打印NG1。

我认为,code将创建一个指针数组两个字符串,并分配到基址,它允许正常的指针运算。但似乎有什么不对的assumption.The第一个printf表明,我的假设是错误的。任何人都可以解释为什么这种行为是观察? (请注意,VS 2012已经抛出一个错误,说太多initalizers那里为海湾合作委员会已抛出了不兼容的指针赋值警告)。我知道的警告,由于不兼容的指针赋值。

I thought that the code will create an array of pointers to two strings and the base address assigned to a, which allows normal pointer arithmetic. but it seems that there is something wrong with the assumption.The first printf suggests that my assumption is wrong. can anyone explain why this behavior is observed? ( note that VS 2012 has thrown an error saying too many initalizers where as GCC has thrown a warning for incompatible pointer assignment). I am aware of the warning due to incompatible pointer assignment.

推荐答案

在你的程序的堆栈内存范围如下:(注意,这不是分配这是错误的之前分配)

The memory range in your program's stack looks like this: (notice that it is not allocated before assignment which is wrong)

char** a = {s, t, r, i, n ,g, 1, \0, s, t, r, i, n, g, 2, \0}

因此​​,当您打印命令:

Therefore when you print the command:

printf("%c", *a);

您的提领是'S'。

在另一方面,当你打印命令:

On the other hand, when you print the command:

 printf("%s", a);

要打印始于指针和'\\ 0'结束的字符串。这就是为什么你看到的输出'字符串1'。

you are printing a string that starts at pointer a and finishes at '\0'. That's why you see the output 'string1'.

最后,当你键入A + 1你在这里增加指针在一个步骤(例如:<一href=\"http://stackoverflow.com/questions/8208021/how-to-increment-a-pointer-address-and-pointers-value\">How递增指针地址和指针的值?)。在这种情况下,因为CHAR **是一个指针,每一个指针是4字节的+1跳4字符前进。
因此,当您打印命令:

Lastly, when you type "a+1" you increase the pointer in one step (example here: How to increment a pointer address and pointer's value?). in this case because char** is a pointer, and every pointer is 4 byte, the "+1" jumps 4 chars forward. Therefore when you print the command:

printf("%s", a+1);

的printf将开始在指针'一'+ 4字节,而在'\\ 0'结束。这就是为什么输出NG1。

The printf starts at the pointer 'a' + 4 bytes and ends at '\0'. That's why the output is 'ng1'.

希望它是很清晰。

这篇关于为const char ** A = {&QUOT;字符串1&QUOT;,&QUOT;字符串2&QUOT;}和指针arithametic的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆