乐闻世界logo
搜索文章和话题

Why can a string be assigned to a char* pointer, but not to a char[] array?

1个答案

1

In C++, string literals, such as "hello", are essentially character arrays that end with a null character (\'\0') to mark the end of the string. This string literal has a fixed address in memory, which can be referenced using a pointer.

Using char* Pointers

When we assign a string literal to a char* pointer, we are essentially storing the memory address of the string in the pointer. For example:

cpp
char* ptr = "hello";

Here, "hello" is a constant string stored in the program's read-only data segment. ptr merely holds the address of this data, so this assignment is valid.

Using char[] Arrays

However, when we attempt to assign a string literal to a character array, the situation is different. For example:

cpp
char arr[] = "hello";

In this case, the content of the string literal "hello" is copied into the arr array. This is done during compile-time initialization, and the array arr actually holds a copy of "hello". After this, arr as an array has its own memory space and can be modified.

However, if we attempt to assign a string to the array after declaration, as follows:

cpp
char arr[10]; arr = "hello"; // Error!

This is not allowed. Because the array name arr is a constant pointer, its value (i.e., the starting address of the array) cannot be changed. Once the array is declared, you cannot make it point to another address; you can only operate or modify the elements within the array using indices.

Summary

When using char* pointers, you can point the pointer to different string literals or character arrays at any time.

When using char[] arrays, you can only initialize string literals at declaration time, and afterward you cannot change the address it points to.

This difference is primarily determined by C++'s type safety and memory management rules.

2024年6月29日 12:07 回复

你的答案