Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a string literal to a char* [duplicate]

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*.

like image 429
Pietro M Avatar asked Dec 02 '11 12:12

Pietro M


People also ask

How do you declare a string literal?

By string literal : Java String literal is created by using double quotes. For Example: String s=“Welcome”; By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”);

Can you modify a string literal in C?

The only difference is that you cannot modify string literals, whereas you can modify arrays. Functions that take a C-style string will be just as happy to accept string literals unless they modify the string (in which case your program will crash).

What is string literal example?

A string literal is a sequence of zero or more characters enclosed within single quotation marks. The following are examples of string literals: 'Hello, world!' 'He said, "Take it or leave it."'

Is it possible to modify a string literal?

C Language Undefined behavior Modify string literalAttempting to modify the string literal has undefined behavior. However, modifying a mutable array of char directly, or through a pointer is naturally not undefined behavior, even if its initializer is a literal string.


2 Answers

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.

like image 103
Wyzard Avatar answered Sep 20 '22 18:09

Wyzard


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";

like image 28
NPE Avatar answered Sep 19 '22 18:09

NPE