Ankit Rustagi
Ankit Rustagi

Reputation: 5637

unexpected output in c (pointers)

Could someone point out the error in this

#include <stdio.h>
void modify (char*s,int x,int y)
{
    s[x]=s[y];
}
main()
{
   char* s = "random";
   modify(s,1,2);
}

The program ends abruptly. I know this may be a very easy question but i am new to c. Thanks !

Upvotes: 0

Views: 89

Answers (2)

Ander Juaristi
Ander Juaristi

Reputation: 328

That's it. I once had the same problem. You should replace this line:

 char *s = "random";

With the following one:

char s[] = "random";

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

It's because it crashes during the assignment in modify. The reason for that is that the pointer points to a constant string, one that can not be modified.

If you want to modify the string, you can declare it as an array instead:

char s[] = "random";

Upvotes: 6

Related Questions