0

I have that code:

#include<stdio.h>

int main()
{
    char *str = "aaaaaaaa";
    char *stt = "bbbbbbbb";
    *str = *stt;
    printf("%s\n", str);

return 0;
}

it gives me an error: Access violation writing location, someone can explain me why and how to over come this?

3
  • it is rewritten prohibited literal string. Commented Dec 8, 2013 at 16:25
  • see this stackoverflow.com/questions/17132248/… Commented Dec 8, 2013 at 16:26
  • 2
    You're not assigning a string pointer to another string pointer. *str = *stt; is the same as str[0] = stt[0]; which attempts to copy the first element from one place to another. Commented Dec 8, 2013 at 16:26

3 Answers 3

3

You are only assigning the first character, which you shouldn't since string literals are not mutable.

Simply use str = stt; to assign the pointers.

BTW, since they are not supposed to be changed, you'd better use const qualified types as in

char const *str = "aaaaaaaa";
Sign up to request clarification or add additional context in comments.

Comments

0

String literals like "aaaaaaaa" are read-only, and your code is trying to overwrite the first character of the string pointed to by str. If that's what you want to do, you'll need to do something like this:

char str[9];
char *stt = "bbbbbbbb";
strcpy(str, "aaaaaaaa");
*str = *stt;
printf("%s\n", str); // prints: baaaaaaa

Of course, it's more likely that what you really want is this:

str = stt;
printf("%s\n", str); // prints: bbbbbbbb

1 Comment

I'll echo @JensGustedt's comment about declaring your strings as char const * instead of char *.
0

A string literal is un-modifiable, i.e, you can't modify a string literal. This is because it is stored on the read only section.

Try this instead

char str[] = "aaaaaaaa";
char stt[] = "bbbbbbbb";  

char *pstr = str;
char *pstt = stt;

pstr = pstt;  
printf("%s\n", ptr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.