13

Possible Duplicate:
How to get rid of deprecated conversion from string constant to ‘char*’ warnings in GCC?

This assignment:

char *pc1 = "test string";

gives me this warning:

warning: deprecated conversion from string constant to 'char*'

while this one seems to be fine:

char *pc2 = (char*)("test string");

Is this one a really better way to proceed?

Notes: for other reasons I cannot use a const char*.

Community
  • 1
  • 1
Pietro M
  • 1,793
  • 3
  • 19
  • 24

3 Answers3

11

A string literal is a const char[] in C++, and may be stored in read-only memory so your program will crash if you try to modify it. Pointing a non-const pointer at it is a bad idea.

Wyzard
  • 32,800
  • 3
  • 63
  • 86
7

In your second example, you must make sure that you don't attempt to modify the the string pointed to by pc2.

If you do need to modify the string, there are several alternatives:

  1. Make a dynamically-allocated copy of the literal (don't forget to free() it when done):

    char *pc3 = strdup("test string"); /* or malloc() + strcpy() */

  2. Use an array instead of a pointer:

    char pc4[] = "test string";

NPE
  • 464,258
  • 100
  • 912
  • 987
  • 1
    +1: Although you should point out that `strdup` is not standard C... – Oliver Charlesworth Dec 02 '11 at 12:25
  • I used `char pc4[] = "test string";` and I get no warnings. I wanted to know if this is the correct way to proceed, or if I am just planting a bug in my code... – Pietro M Dec 02 '11 at 15:24
  • @PietroM: No, you're not planting any bugs, as long as you bear in mind that the allocated array is `strlen("test string")+1` bytes long. If you need a longer array, you can specify the length explicitly: `char pc4[32] = "test string";` – NPE Dec 02 '11 at 15:28
  • To be more precise, I used `static char pc4[] = "test string";` and I get no warnings. I did it static because it is inside a function, and I want the string to be available even when out of the function. I wanted to know if this is the correct way to proceed, or if I am just planting a bug in my code... – Pietro M Dec 02 '11 at 15:33
5

That depends on whether you need to modify the string literal or not. If yes,

char pc1[] = "test string";
Mahesh
  • 33,625
  • 17
  • 84
  • 113