Error on a simple string pointer

Hello,

so below, trying to learn about string and writing this out, watching an example on youtube, when he compiles it works, when i compile and run it, it gives me this error message:

an unhandled exception of type 'System.AccessViolationException' Occured in tutorial_04.exe

Additional Information: Attempted to read or write protected memory. This is often an indication that other memory is corrupted.

is this something regarding my own PC, or maybe my code?

1
2
3
4
5
6
7
	char* str = "Steven";

	str[2] = 'a';

	std::cout << str << std::endl;

	std::cin.get();


I know if i change it to be:
1
2
3
4
5
6
       char str[] = "Steven";
       *(str+0) = 'a';
	std::cout << str << std::endl;

	std::cin.get();


that works, but the first code didnt... why? :(

thanks in advance.
In your first example, str isn't an array. It's just a pointer. It's pointing to a string literal - this is stored in a bit of memory that's not available for you to try and overwrite.

In line 3, you're trying to overwrite a bit of memory with the string 'a'. This is illegal.

Do you understand what a pointer is? Do you understand what an array is? Do you understand the difference between the two?

EDIT: And while it may compile, your compiler should be warning you that you shouldn't be doing that.
Ya i understand now the pointer is really storing the point of memory address, and the array is really just a series of elements. thought if i did double quotes it would turn it into a string, my fault, but makes sense, big thank you MikeyBoy :)
You're welcome! Glad it helped.
Topic archived. No new replies allowed.