Modifying char arrays after declaration.

in this theoretical program:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

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

--Rollie
Character literals must be enclosed in single quotes:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int main()
{
    char test[] = "Thes is a test";
    test[2] = 'i';
    cout << test << endl;
    system("PAUSE");
    return 0;
}

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 = new char[20];
    strcpy(test, "Thes is a test");
    test[2] = 'i'; // should now work
    std::cout << test;
    delete[] test; // must remember to free the memory
}
Galik wrote:
Your problem is that you are trying to write to read-only memory.

I don't think that's the case.

char test[] = "Thes is a test";

is equivalent to

char test[] = {'T','h','e','s',' ','i','s',' ','a',' ','t','e','s','t','\0'}; AFAIK

EDIT: It would be like you said if he did:

char * test = "Thes is a test";
Last edited on
@m4ster r0shi

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.

Galik wrote:
My bad...

Not at all! :) A friend of mine likes to say:

m4ster r0shi's friend likes to say:
Never see anything that you do as a failure, but see it as an
accomplishment. Then you have never failed; you have always learned.
Last edited on
Topic archived. No new replies allowed.