char *str, *str = 'X' error,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
        char* str = new char[10];
	str = "Hello";           
	//*(str + 1) = 'a';             // crush if uncomment this line
        cout << *(str + 1) << endl;   // this works fine


//==========================================
	int arr[] = {2, 3, 4, 5};

	int* x = arr;
	*(x + 2) = 2;
	(x + 2) = &y;                  // this is fine, why the type is char* will crush??
	cout << *(x + 2) << endl;


	


when the type is char*, the assignment cause crush while in an int array, it works fine, why?

plus, if I want to define a pointer array, what should I do?

int* arr[] = {2, 3, 4, 5}; // this is wrong, "invalid convention from int to int*", what should I do?
Line 2 is your problem. You're probably assuming that line 2 is a copy statement. It is not. It is an assignment of a pointer. "hello" is actually a pointer to a const char array stored by the compiler, usually in non-modifiable code space. After you execute line 2, str points to that const char array.
You've also created a memory leak, because the array you allocated in line 1 is no longer addressable. i.e. You can't delete it.

Line 3 attempts to store an 'a' into that const char array (non-modifiable code space). That's what causing the crash.

Your int example works because you're not trying to store into a const array in non-modifiable code space.
That's a good explanation of the problem. Now the solution:

1.
1
2
char str[] = "Hello";
*(str+1) = 'a';

or
1
2
3
char* str = new char[10]; // remember to delete this later
strcpy(str, "Hello");  // #include <cstring>
*(str+1) = 'a';


2. I'm not sure, but I have heard that char* are a "special" type.

3. For a pointer array, do this:
1
2
3
int** arr = new int*[4]; // an array of 4 more arrays
arr[0] = new int[4]; // arr[0] is now an array, you may fill it with {2,3,4,5}
arr[0][0]; // this will return 2 

or
int arr[4][4] = {{2,3,4,5},{6,7,8,9},{10,11,12,13},{14,15,16,17}};
or
1
2
3
4
5
int* a = new int;
int* b = new int;
int* c = new int;
int* d = new int;
int* arr[] = {a,b,c,d}; // a,b,c,d need to have addresses. 
Last edited on
Topic archived. No new replies allowed.