4

Possible Duplicate:
What is the difference between char s[] and char *s in C?

There's a program:

#include<stdio.h>

int main()
{
    char str[20] = "Hello";
    char *const p=str;
    *p='M';
    printf("%s\n", str);
    return 0;
}

This prints Mello as the answer.. But since p is a constant pointer, shouldn't it give an error?

Community
  • 1
  • 1
Rebooting
  • 2,762
  • 11
  • 47
  • 70

4 Answers4

15

It's a contant pointer, exactly. You can't change where it points. You can change what it points.

const char *p;  // a pointer to const char
char * const p; // a const pointer to char
const char * const p; //combined...

The easiest way to memorize the syntax is to not memorize it at all. Just read the declaration from right to left :-)

emesx
  • 12,555
  • 10
  • 58
  • 91
2

char *const p; is a constant pointer to a char. So modifying the value pointed by p is perfectly legal.

There's a detailed explanation: const char vs. char const vs const *char const

Community
  • 1
  • 1
P.P
  • 117,907
  • 20
  • 175
  • 238
0

You can't change the value of p, but you can change the value of *p.

If you had written char const *p=str or const char *p=str, then you would not have been able to modify *p.

John Bode
  • 119,563
  • 19
  • 122
  • 198
0

There is a difference between a constant pointer and pointer to constant data. Consider these four:

const char * p=str;  // p[0] is const
char const * p=str;  // same
char *const p=str;   // p is const. *p is not
char const *const p=str; // p is const, p[0] also
Pavel Radzivilovsky
  • 18,794
  • 5
  • 57
  • 67