为const char **和char ** [英] const char ** and char **
问题描述
code 1:没有警告,没有错误。工作完美。
的#include<&stdio.h中GT;无效printP(为const char * P)
{
的printf(为const char * p是:%P \\ N,P);
如果(p)的
的printf(%S \\ n,p)的;
}无效printP2P(为const char ** P)
{
的printf(为const char ** P指针:%P \\ N,* P);
如果(P&放大器;及(* P))
的printf(%S \\ n,* P);
}诠释的main()
{
所以char a [] =Hello World的;
为const char * p = A;
为const char ** P2P =安培; P;
printP(P);
printP2P(P2P);
返回0;
}
code 2:可以正常工作
。
警告:从兼容的指针类型[默认启用]初始化
块引用>为const char * p = A;
==>
的char * p = A;code 3:Segementation故障
警告:从兼容的指针类型[默认启用]初始化
块引用>为const char ** P2P =安培; P;
==>
为const char ** P2P =安培; A;问题:
- 为什么code 2可以工作,但code 3有一个节段的错吗?
2,当了一通
聊天*
到为const char *
,没有警告或错误发生了,但是当我分配的char **
到为const char **
,我得到了一个警告,为什么?解决方案假设
A [] = 0x100处 - ^ hèL LØW 0 R L D = 0x48 0x65 0x6c 0x6c ...
P =为0x200
P2P = 0x500处有关案件3
P2P =放大器;一
P2P = 0x100的和当您尝试使用
* P2P
您正试图*为0x100
这是读取内存地址打印保存在的0x100
是0x4865
(假设2个字节的地址和做客场字节序)。地址0x4865
最有可能是无效的,读它会导致分段错误。有关第二种情况,其直线前进......
P2P =安培,P
P2P =为0x200
* P2P = * =为0x200 0x100处混淆的部分是,阵列地址
&放大器;一个
是一样的A
这是一样的&安培; A [0]
Code 1: no warning , no error . work perfect.
#include <stdio.h> void printP(const char *p) { printf("const char *p is : %p\n",p); if( p ) printf("%s\n",p); } void printP2P(const char **p) { printf("const char **p pointer to : %p\n",*p); if( p &&(*p) ) printf("%s\n",*p); } int main() { char a[] = "Hello World"; const char *p = a; const char **p2p = &p; printP(p); printP2P(p2p); return 0; }
Code 2: can work.
warning: initialization from incompatible pointer type [enabled by default]
const char *p = a; ==> char *p = a;
Code 3 : Segementation fault.
warning: initialization from incompatible pointer type [enabled by default]
const char **p2p = &p; ==> const char **p2p = &a;
Problem:
- Why code 2 could work but code 3 got a segement fault ?
2.When a pass
chat *
toconst char *
, no warning or error happened ,but when I assignmentchar **
toconst char **
, I got a warning, why?解决方案Assume
a[] = 0x100 - H e l l o w o r l d = 0x48 0x65 0x6c 0x6c ... p = 0x200 p2p = 0x500
For 3rd case
p2p = &a p2p = 0x100
and when you try to print it using
*p2p
you are trying*0x100
which is reading memory at address stored at0x100
which is0x4865
(assuming 2 bytes address and doing away to endianness). The address0x4865
most likely is not valid and reading it causes segmentation fault.For 2nd case, its straight forward ...
p2p = &p p2p = 0x200 *p2p = *0x200 = 0x100
Confusing part is that for array address
&a
is same asa
which is same as&a[0]
.这篇关于为const char **和char **的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!