11

I am working with strings .

Whenever I execute the following program I get an error as deprecated conversion from string constant to 'char' in c* on the line char *p = "hello"

What am i doing wrong?

What does this error mean ?How can i correct it?

My code is:

#include<stdio.h>
int main()
{
    char *p = "hello";
    printf("%s",p+1);
    return 0;
}
Justin Meiners
  • 10,754
  • 6
  • 50
  • 92
user2227862
  • 595
  • 3
  • 9
  • 16

2 Answers2

18

This should be a warning (though you may have set your compiler to treat warnings as errors, which is often a good idea).

What you want is: char const *p = "hello"; instead.

Attempting to modify a string literal gives undefined behavior. The const prevents you from doing that by accident (i.e., code that attempts to write via the pointer won't compile, unless you remove the const qualifier, such as with a cast).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
5

This is a warning, because "Hello" string is a constant and you are trying to store that in non const char*. To slove the problem either make it

const char* p = "Hello" or char[] p = "Hello"

Daemon
  • 1,575
  • 1
  • 17
  • 37
  • not `const char* p` but `char const *p` some compioler may give you waring for `const char*` – Grijesh Chauhan May 27 '13 at 06:01
  • 4
    @GrijeshChauhan: A compiler *could* generate a warning for almost any (or no) reason, but I'd be at least a little surprised to see one for putting `const` before type instead of after. The standard requires either/both to be accepted. – Jerry Coffin May 27 '13 at 06:04
  • 1
    @GrijeshChauhan can you plz specify which compiler. Because const char and char const both are same I think – Daemon May 27 '13 at 06:07
  • what? I thought const char* is a pointer to a constant char, where as char const* is a constant pointer to a char. in which case only const char* should fix the warning – matt May 27 '13 at 06:10
  • I read it some where in past about it, read on [wiki here: const-correctness](http://en.wikipedia.org/wiki/Const-correctness) – Grijesh Chauhan May 27 '13 at 06:11
  • 2
    @matt const char* and char const* both will make content const and if you want to make pointer const then const shoud appear in between char *const ptr; – Daemon May 27 '13 at 06:13
  • 5
    `const char*` and `char const*` are equivalent, both are pointers to constant data (the latter is somewhat poor style however). The placement of the `*` in relation to the `const` keyword is what matters. Don't mix this up with `char* const`, which is a pointer to constant data. – Lundin May 27 '13 at 06:14