const pointer versus const content pointed to by pointer

const pointer versus const content pointed to by pointer

Post by Disc Magne » Fri, 07 May 2010 19:10:56


I wrote this code.

disc@magnet:~$ cat const.c
#include <stdio.h>

int main()
{
char s[] = "hello, world\n";
char r[] = "hello, pluto\n";
const char *p = s;
char const *q = r;

p[1] = 'a';
q[1] = 'a';

printf("p: %s\n", p);
printf("q: %s\n", q);
return 0;
}

Got these errors:

disc@magnet:~$ gcc const.c
const.c: In function 'main':
const.c:10: error: assignment of read-only location '*(p + 1u)'
const.c:11: error: assignment of read-only location '*(q + 1u)'

This shows that both syntaxes: const char *p as well as char const *p
makes the content of the array pointed to by p, is constant. However,
what I want is that p itself should be constant. That is, it should be
possible to assign to p only once.

I want a behavior like this:

disc@magnet:~$ cat int.c
#include <stdio.h>
int main()
{
const int p = 10;
p = 20;
return 0;
}

disc@magnet:~$ gcc int.c
int.c: In function 'main':
int.c:5: error: assignment of read-only variable 'p'

where p is a char *. What is the right syntax?
 
 
 

const pointer versus const content pointed to by pointer

Post by Ian Collin » Fri, 07 May 2010 19:27:57


No, it doesn't. p is a pointer to const char.


You want char* const p = s;

--
Ian Collins