overriding constant char pointer.

Here is a sample program to remove trailing spaces.When i try to place '\0' after '.' , it gives an error saying cannot overwrite the memory location.
I'm using VS2008.
#include<stdio.h>
#include<string.h>

void trim()
{
int m;
int n;
char *str="hi how are you. ";
char ch;
printf("%s\n",str);
printf("%d\n",n=strlen(str));
m=n-1;
while(m>0)
{
if(*(str+m)!=' ')
{
*(str+m+1)='\0'; // put the '\0' after '.'
break;
}
else
m--;
}
printf("%s\n",str);
printf("%d\n",n=strlen(str));
}


void main()
{
trim();
}



closed account (zb0S216C)
beginner2011 wrote:
 
char *str="hi how are you. ";

String literals are constant. Perhaps using arrays:

1
2
3
char string_[] = "A sample string...";

string_[0] = ...; // OK. 

Here, the compiler will count the number of characters within the string, will create the string_ array based on the size of the string, and will populate the array with the characters of the string.

Wazzak
Last edited on
String literals gives you a const char array so it should really be const char *str="hi how are you. ";

If you want str to be an array that you can change you can initialize str like: char str[] = "hi how are you. ";
In C++ code, text you write into the code like this:

"hi how are you. "

is known as a string literal. It is written into the actual executable file, and cannot be altered during execution. It is read-only. So you're trying to write over the top of something that is read only.

If you want to do this, you will have to work on data that is not read-only. You can do this by, for example, copying the char array, and then you can play with that copy. You can copy it yourself, or you can create something like Peter87 suggested, which will handle that for you.

A much better option is to stop using char arrays and use C++ strings.

Edit: I was so ninjared. :(

Last edited on
Thanks guys for the wonderful explanation.
So even if i dont specify const keyword in the below line still it will be a character string constant.
char *str="hi how are you. ";

Thanks once again.
There is a difference between character string literals in C++ and in C. In C++ a character string literal has type of array of const char while in C it has type of array of char

However though in C a string literal type has no the const qualifier you may not change it according to the C standard.

"If the program attempts to modify such an array, the behavior is
undefined."
Last edited on
Topic archived. No new replies allowed.