Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constant pointer in C [duplicate]

Tags:

c

pointers

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?

like image 227
Chandeep Avatar asked Dec 03 '22 02:12

Chandeep


1 Answers

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 :-)

like image 193
emesx Avatar answered Dec 23 '22 10:12

emesx