0

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?

4 Answers 4

4

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];
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

5 Comments

If it cannot be initialized by a string, what should I use instead?
doesn't std::string have a c_str() method that returns a char* array? (I'm not looking at the docs... just memory here)
What C Johnson means is that using char a[] = msg1.c_str() can do the trick.
It returns a const char *. The initializers of the char array have to be characters or something that can be converted to a char
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.
-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.