1

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:

  1. Why code 2 could work but code 3 got a segement fault ?

2.When a pass chat * to const char * , no warning or error happened ,but when I assignment char ** to const char **, I got a warning, why?

1 Answer 1

3

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 at 0x100 which is 0x4865 (assuming 2 bytes address and doing away to endianness). The address 0x4865 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 as a which is same as &a[0].

3
  • +1. Not so confusing after awhile. The C-standard covers it well in 6.2.5.20, and the second half of this answer beats it somewhat to death.
    – WhozCraig
    Commented Sep 7, 2013 at 10:13
  • @WhozCraig, yeah but I think OP is confused with that hence got that question.
    – Rohan
    Commented Sep 7, 2013 at 10:14
  • I completely concur, thus "after awhile" and not right of the gate.
    – WhozCraig
    Commented Sep 7, 2013 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.