tags:

views:

66

answers:

5

Hi, I am writing a program that needs to take text input, and modify individual characters. I am doing this by using an array of characters, like so:

char s[] = "test";
s[0] = '1';
cout << s;

(Returns: "1est")

But if I try and use a variable, like so:

string msg1 = "test";
char s2[] = msg1;
s2[0] = '1';
cout << s1[0]

I get an error: error: initializer fails to determine size of 's2'

Why does this happen?

A: 

I think char a[] can't be initialized by a string. Edit: "a string" is actually a c-type string (char array with '\0' at the end).

LLS
If it cannot be initialized by a string, what should I use instead?
Strigoides
doesn't std::string have a c_str() method that returns a char* array? (I'm not looking at the docs... just memory here)
C Johnson
What C Johnson means is that using char a[] = msg1.c_str() can do the trick.
LLS
It returns a const char *. The initializers of the char array have to be characters or something that can be converted to a char
Chubsdad
It *can* be initialized by a string, but it has to be a constant string whose value is known at compile time, and not the result of some expression.
Nathan Fellman
+2  A: 

The space for all the variables is allocated at compile time. You're asking the compiler to allocate space for an array of chars called s2, but not telling it how long to make it.

The way to do it is to declare a pointer to char and dynamically allocate it:

char *s2;

s2 = malloc(1+msg1.length()); // don't forget to free!!!!
s2 = msg1; // I forget if the string class can implicitly be converted to char*

s2[0] = '1'

...
free(s2);
Nathan Fellman
+4  A: 

C-style arrays require literal values for initialization. Why use C-style arrays at all? Why not just use std::string...

string msg1 = "test";
string s2 = msg1;
s2[0] = '1';
cout << s2[0];
nobar
A: 

This shows the difference between initialization, when a chunk of memory is set aside and data is put in it, and assignment, when data is put into a chunk of memory. C++ happens to allow the shortcut that you can initialize a character array by using double-quotation marks like this

char s[] = "test";

But that's sort of a special case. Unless you want to manually set aside the memory and then assign values using malloc/free, you should probably just use a second C++-style string.

Spencer Nelson
A: 

$8.5.1 and $8.5.2 talk about rules related to initialization of aggregates.

Chubsdad