#include <iostream>
usingnamespace std;
int main()
{
char test[] = "Thes is a test";
test[2] = "i";
cout << test;
system("PAUSE");
return 0;
}
(i say theoretical because my actual source code is too large and multiple files)
how would I modify an array of chars after it has been defined?
it produces an error when I try as demonstrated by line 8.
"x" is an char array of size 1, whereas 'x' is a char. Since you are altering a specific character in array test, the right hand side must also be a char. Your error should give you some indication of this (ERROR: Cannot convert from 'char []' to 'char' at line 8, or something like that).
Your problem is that you are trying to write to read-only memory. Your string "Thes is a test" is a constant char array but C++ is lenient and lets you assign its address to a non-const char*.
If you want modifiable memory you need to use an array created on the stack or allocated from the free-store:
1 2 3 4 5 6 7
int main()
{
char test[20];
strcpy(test, "Thes is a test");
test[2] = 'i'; // should now work
std::cout << test;
}
There I created the array on the stack and copied the read-only string literal into the write accessible memory.
Alternative you can allocate memory from the free-store:
1 2 3 4 5 6 7 8
int main()
{
char* test = newchar[20];
strcpy(test, "Thes is a test");
test[2] = 'i'; // should now work
std::cout << test;
delete[] test; // must remember to free the memory
}
My bad, you are quite correct. In fact char test[] = "Thes is a test"; is far more efficient than using an initializer using GCC in x86. On my system it breaks the string literal down into 32bit words and writes them to the stack. The initializer writes each char individually.