const pointer versus const content pointed to by pointer


D

Disc Magnet

I wrote this code.

[email protected]:~$ 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:

[email protected]:~$ 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:

[email protected]:~$ cat int.c
#include <stdio.h>
int main()
{
const int p = 10;
p = 20;
return 0;
}

[email protected]:~$ 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?
 
Ad

Advertisements

I

Ian Collins

I wrote this code.

[email protected]:~$ 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:

[email protected]:~$ 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;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top