1

I have declared the string array in my code as follows.

char *arr[] ={ 
"xyz",
"abc",
"pqr",
NULL
};

When compile then got following warning

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

i know that "xyz" and other string literal are const char and my array is char* so have resolve it by declaring my array const char* arr but i loss the control to point this array in another pointer. So to resolve above issue have declared array as follows

 char *arr[] ={ 
    (char *)"xyz",
    (char *)"abc",
    (char *)"pqr",
    NULL
    };

But this type of declaration not fair when need large array (more then 100 string array). So any one have idea to resolve it by another way.

Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73

3 Answers3

4

You don't lose any re-pointing options by making the array a const char* arr[]. Note that there's a huge difference between const char * p (a mutable pointer to an immutable char) and a char * const p (an immutable pointer to a mutable char). This code is perfectly valid:

const char *arr[] = {
  "xyz",
  "abc",
  "pqr",
  NULL
};

arr[1] = "ghi";

Live example

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

There is a difference between a const char* and char *const if your pointer is a const char* you can still point it to another location but you cannot modify the elements it contains. The correct solution in this case is to make the array const char*.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
0

String literals are constant, so you need const pointers to refer to them:

const char *arr[] = {
    // whatever
};

Historically, it used to be possible (but dangerous) to convert string literals to non-const char*, for compatibility with ancient code that didn't know about const. This conversion has been deprecated for many years, and finally removed from the language in 2011.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • I don't think this post addresses the question OP apparently knows about `const char*` and literals but has problems using this type. – Ivaylo Strandjev Jan 02 '14 at 13:03
  • @IvayloStrandjev: If that is the case, the solution will depend very much on why there are "problems" with `const char*`; and should probably be solved by addressing those "problems", not by subverting the type system. – Mike Seymour Jan 02 '14 at 13:17
  • I agree. The question does not contain enough information to give a complete answer. – Ivaylo Strandjev Jan 02 '14 at 13:19