On 05/ 6/10 10:10 PM, Disc Magnet wrote:
> 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.
No, it doesn't. p is a pointer to const char.
> However,
> what I want is that p itself should be constant. That is, it should be
> possible to assign to p only once.
You want char* const p = s;
--
Ian Collins
|