pointer and char string help

I was trying to get a better understanding of pointers and c style strings but I'm having an issue grasping why this is crashing. I know it has to do with str[1] = 'b'; but I can't understand why that isn't possible in this case but would be if I had created the string with char str[10];

I was under the impression that a char array was a pointer to the first char and so these would be interchangeable?

Any help would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
int main() {
  void* vp;
  char* str = new char[10];
  str = "abcdefg/0";
  vp = str;
  std::cout << *(((char*)vp) + 3) << std::endl;

  str[1] = 'B';
  std::cout << str[1] << std::endl;

  return 0;
}
Last edited on
Line 3 allocates some characters for str,
then line 4 immediately throws them away from the constant string in line 4. This creates a memory leak.

Two things to note there:
- You don't need a null terminator (yours in incorrect anyway, it should be \0, not /0) since the "" automatically include a null terminator.
- You probably wanted to put that data inside the data you had allocated on line 3. Use strcpy for that purpose.

Line 8 (I assume) crashes because you are trying to write to a position in the constant string on line 4.

Once you've fixed the above, you also should delete[] str before finishing the program.
@Coios
I was under the impression that a char array was a pointer to the first char and so these would be interchangeable?


Arrays and pointers are different entities. It is seen from their definitions

char s[10];
char *p;

Array names used in expressions are converted to the pointer to their first elements.

Let consider statements

char* str = new char[10];
str = "abcdefg/0";

In the first statement you are allocating in the heap an unnamed array of 10 elements. Operator new returns pointer to the first element of the allocated array.

In the second statement in the left side there is the same pointer while in the second part there is an array of 10 elements. The string literal has type const char[10].
As I said in expressions arrays are converted to pointers of their first elements.
So after executing this statement the value of str will be changed. Early it was equal to the address of the allocated memory. Now it contains another address that is the address of the first element of the string literal.
The compiler should issue at least a warning that you are trying to assign const char * (the string literal is converted to the pointer to the first element) to the char *. In any case you may not change the array of the string literal that now is pointed by str.
Last edited on
Thank you both! Definitely clears up pointers and fixed some of my bad practices.
Topic archived. No new replies allowed.