how to catch exception modifications to the array "const pointer"

Hello.
I write function whose Modifying array (char), how to check that variable of function is non-const.

implementation
1
2
3
4
5
6
7
8
9
10
11
void modifying(char* arr){
 // how to check that [arr] is dynamical or const 
// or how to throw exception bellow not help
/*	try {
		arr[0] = 'a';
	} catch(...) {
		throw;
	}*/

 arr[0] = 'a';
}


using in main
1
2
3
4
5
6
7
char* arr1 = new char[2];
arr1[1] = '\0';
arr1[0] = 'b';
modifying(arr); // ok

char* arr2 = "ddd";
modifying(arr2); //error 

Last edited on
To store a pointer to a string literal you should use a pointer to a const.
const char* arr2 = "ddd";
Now you will get a compiler error when you try to call modifying(arr2);

char* arr2 = "ddd"; This was deprecated in C++03 and is no longer valid code in C++11. If you turn up you compiler's warning level you should be able to get a warning when you try to do this.


Hi

First you define the parameter of the function to be const or not.
1
2
3
4
5
6
7
8
9
10
// this function can only read the arr, but cant modify it
void cantModify(const char* arr){

}

// this function can modify the arr
void canModify(char* arr){

}


Second you have problem in your main line 6! you assign some characters to your arr2 which was not allocared!

hope it helps
Last edited on
Topic archived. No new replies allowed.