very simple program crashes

just using a swap function to swap a string but the program crashes I can't see where and why the program crashes it looks logically correct to me yet crashes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>
using namespace std;


void swap(char* array,int start,int end){

	char temp;
	temp = array[start];
	array[start] = array[end];
	array[end] = temp;

}


int main() {

	char *str = "Bill";
	swap(str,0,1);

}
You are trying to alter a const. In main str should be defined as const char* = "Bill";.
thanks jlb

but how am I trying to alter a const?

I never declared str as const?
Because "Bill" is a const and you're playing with a pointer, not an array of char.

You should have gotten a warning/error if you're using a properly configured modern compiler something like:

main.cpp|17|error: ISO C++ forbids converting a string constant to ‘char*’ [-Wpedantic]|

The other option would be to use an array instead of the pointer:

char str[] = "Bill";

Remember there are subtle differences between arrays and pointers.

By the way why are you using C-strings instead of std::string?

I never declared str as const?

No, but "Bill" is implicitly const.
Thanks guys I never knew that

yeah would be a better idea to use std::string but I'm just playing around with c style strings
Topic archived. No new replies allowed.