Lidong Guo
Lidong Guo

Reputation: 2857

const char ** and char **

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?

Upvotes: 1

Views: 296

Answers (1)

Rohan
Rohan

Reputation: 53316

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].

Upvotes: 3

Related Questions