0

I'm trying editing the content of location pointed by char* const, but this doesn't work.

I'm trying to implement this question answer What is the difference between char s[] and char *s?

Exactly this part:

char* const 

is an immutable pointer (it cannot point to any other location) but the contents of location at which it points is mutable.

I know about literal string which is immutable, but here I'm using const so may this be different. Here is my code:

#include <stdio.h>
int main()
{
  char* const address="mutable content";
  strcpy(&address,"succeed");
  printf("%s\n",address);
  return 0 ;
}
Community
  • 1
  • 1
  • You try to copy the string literal `"succeed"` to the address where your pointer `address` is. So you change the value of the pointer (which is UB because the pointer is const), not the value where the pointer points to. – mch Sep 25 '16 at 22:08
  • 2
    "mutable content" is not mutable content even though you wrote that it is. – user253751 Sep 25 '16 at 22:11
  • So, How to change the content value ? –  Sep 25 '16 at 22:12
  • 2
    See: [What is the difference between char s\[\] and char *s in C?](http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c) – Greg Bowser Sep 25 '16 at 22:12
  • 1
    I'm trying to implement this question answer http://stackoverflow.com/questions/9834067/difference-between-char-and-const-char –  Sep 25 '16 at 22:14
  • this answer exactly : char* const is an immutable pointer (it cannot point to any other location) but the contents of location at which it points are mutable. –  Sep 25 '16 at 22:15
  • @YasserMohamed A char* *can* point at immutable content, such as a string literal, although it's discouraged. – user253751 Sep 25 '16 at 22:19
  • What makes you think just because **you guarantee** to the compiler you will not change **the pointer** does change anything for **the object it points to**? – too honest for this site Sep 25 '16 at 22:19
  • I want to understand the question I did mention its link before. so did try this code. I know about literal string and char pointer, but thought may const word make it different. wish someone kindly make it clear –  Sep 25 '16 at 22:23
  • You should call `strcpy(address, "succeed");`, without the ampersand. The ampersand is the "address-of" operator, which returns a pointer to the operand. `strcpy` takes a pointer to a char, but when you use the ampersand you're passing in a pointer to a pointer to a char. – Ray Hamel Sep 25 '16 at 23:28

0 Answers0