A 'char * string' assigning problem

L

lili

Please forgive my poor english.The following is my code:
-------*************************************************---------
#include <stdio.h>
#include <string.h>

int main()
{
char* teststr = "hello";
char* yes = teststr;
*(++yes) = 'w';
printf(yes);
}
-------*************************************************---------
print: segment error
Why did i got a 'segment error'?
but
-------*************************************************---------
#include <stdio.h>
#include <string.h>

int main()
{
char teststr[20] = "hello";
char* yes = teststr;
*(++yes) = 'w';
printf(yes);
}
-------*************************************************---------
print: hwllo
or
-------*************************************************---------
#include <stdio.h>
#include <string.h>

int main()
{
char* teststr = "hello";
char* yes = teststr;
printf("%c\n", *(++yes));
}
-------*************************************************---------
print: e

is no problem.
Can anyone help me , Thank you!
 
B

Ben Bacarisse

lili said:
Please forgive my poor english.The following is my code:
-------*************************************************---------
#include <stdio.h>
#include <string.h>

int main()
{
char* teststr = "hello";

The arrays that result from a string literal are unmodifiable. The
effect of doing so is undefined.
char* yes = teststr;
*(++yes) = 'w';

'yes' is the same pointer as 'teststr' and 'teststr' points at an
unmodifiable array of characters. Trying to put that 'w' where the
'e' is in the original string causes anything to happen. A segfault
one of the most helpful outcomes.

Most people prefer to write:

const char *teststr = "hello";

so as to be reminded when an attempt is made to modify the target
string.
printf(yes);
}
-------*************************************************---------
print: segment error
Why did i got a 'segment error'?
but
-------*************************************************---------
#include <stdio.h>
#include <string.h>

int main()
{
char teststr[20] = "hello";

teststr is now a plain local array whose elements get initialised
using the string hello. The chars in teststr can be modified with no
ill effects.
char* yes = teststr;
*(++yes) = 'w';
printf(yes);
}
-------*************************************************---------
print: hwllo
or
-------*************************************************---------
#include <stdio.h>
#include <string.h>

int main()
{
char* teststr = "hello";
char* yes = teststr;
printf("%c\n", *(++yes));

And here there is no modification to cause a problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top