Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main() {
	char *string = "Programming is EPIC!";
	*string = 'K';

	printf("%s\n", string);

	_getch();
	return EXIT_SUCCESS;
}


This code does not compile and gives errors! I read this example in a book and it says that it should compile but the compiler gives errors!

NOTE: If compiling on Linux, please remove the <conio.h> and _getch(); function.
Posted
Comments
Mohibur Rashid 27-Feb-15 1:59am    
yup, remove getch or anything like that.
and char *string = "Programming is EPIC!"; this type of declaration is dropped. you better try
char string[] = "Programming is EPIC!";
Member 11476553 27-Feb-15 5:15am    
thank you @mohibur it works

It is better to provide some memory to the string and than fill it.

char string[30];
strcpy(string,"Programming is EPIC!");
string[0] = 'K';


You better look out for some string library to take care about such annoying tasks. ;-)
So such code would do the job
C++
std_string string = "Programming is EPIC!";
string[0] = 'K';
 
Share this answer
 
Comments
CPallini 27-Feb-15 2:24am    
5.Of course you don't need std::string to do
char string[] = "Programming is EPIC";
string[0] = 'K';
BTW you should replace the underscore with the scope operator ::
The problem is that your string is a constant: so when you try to alter it in any way, you will get an "Access violation" exception and your program will crash.

What you need to do is make a copy of it into an array, either manually:
C#
char* inp = "Programming is EPIC!";
char string[100];
int i;

for (i= 0; i < 100; i++)
    {
    string[i] = inp[i];
    if (string[i] == '\0') break;
    }
*string = 'K';
Or automatically:
C#
char string[] = "Programming is EPIC!";
*string = 'K';
 
Share this answer
 
Comments
CPallini 27-Feb-15 2:23am    
5.The second one is far better, in my opinion.
OriginalGriff 27-Feb-15 3:17am    
I agree - the first just shows what the second is doing under the hood.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900