The two declarations are different Can you explain where these declarations are applicable effectivelyconst char *s; char const *s;

Showing Answers 1 - 10 of 10 Answers

umeshknair

  • Sep 20th, 2006
 

The const keYword is used a bit differentlY when pointers are involved. These two declarations are not equivalent:const char *s; char const *s;In the first example, the char *s is constant; i.e.You cannot chanGe the content of char. In the second example, the pointer to char *s itself is constant; i.e. You can chanGe the content, just fine, but...You cannot chanGe the pointer itself; i.e.pointer arithmetic like *s++ etc.Have a Great daY!wait! I forGot to tell u onethinG todaY is mY birthdaY.-dot-

  Was this answer useful?  Yes

Raj

  • Sep 21st, 2006
 

These two declarations are same. We can't change the value pointed by the pointer.

  Was this answer useful?  Yes

Mamadur Nagaraj

  • Sep 27th, 2006
 

Sorry, I checked the u r comment late.

Anyhow Belated birthday wishes.

  Was this answer useful?  Yes

These two declations are same... a rule of thumb to read them: Starting from *, move towards left...
so 1st will be read as "pointer to char constant:" , & 2nd as "pointer to a constant char"..... as u see both are equivalent.... Both are pointers to char constant, so pointer can be changed to point to something else, but the char (string) can't be changed...
however consider following declarations:
const *char s;
char *const s;
here, both are "Constant pointers to char".....
regards
Vipin

  Was this answer useful?  Yes

manik sheeri

  • Nov 7th, 2006
 

i think that the both declarations are the sameconst char *s;char const *s;in both cases the string to which s will point cant be changed.but something likechar * const s;means that the pointer is held const and not the string. we can change the contents of the string to which s points but we cant change the contents of s;also const char * const s;means that both pointer and string are held constant and cant be changed.

  Was this answer useful?  Yes

ardashev

  • Nov 17th, 2007
 

#include <stdlib.h>
int main()
{
    const char *pr1 = malloc(4);
    char  const *pr2 = malloc(4);
    char * const pr3 = malloc(4);
    pr1[1] = 'W';
    pr2[1] = 'W';
    pr3[1] = 'W';
    pr1++;
    pr2++;
    pr3++;
    return 0;
}

gcc t.c -o t.exe
t.c: In function ‘main’:
t.c:7: error: assignment of read-only location
t.c:8: error: assignment of read-only location
t.c:12: error: increment of read-only variable ‘pr3’




  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions