简体   繁体   English

c 和 c++ 字符指针之间的区别

[英]difference between c and c++ char pointers

In C this works totally fine:在 C 这工作得很好:

char* Test = (char*) malloc(sizeof(char));
Test = "Hey";

Meanwhile in Cpp it throws me this error:同时在 Cpp 它给我这个错误:

char* Test = (char*)malloc(sizeof(char));
Test = "Hey";

a value of type "const char *" cannot be assigned to an entity of type "char *" “const char *”类型的值不能分配给“char *”类型的实体

What is the difference between these two and why is a pointer in Cpp alsways a const and cant be modified later?这两者有什么区别,为什么Cpp中的指针总是一个const,以后不能修改?

First of all the both code snippets (if to add the qualifier const to the pointer in the second code snippet) produce a memory leak because at first memory was allocated and its address was assigned to the pointer Test and then the pointer was reassigned with the address of the first character of a string literal.首先,这两个代码片段(如果将限定符const添加到第二个代码片段中的指针)会产生 memory 泄漏,因为首先分配了 memory 并将其地址分配给指针Test ,然后使用指针重新分配指针字符串文字的第一个字符的地址。 As a result the address of the allocated memory is;lost.结果,分配的 memory 的地址丢失了。

In C++ opposite to C string literals have types of constant character arrays.在 C++ 中,与 C 相对的字符串文字具有常量字符 arrays 的类型。

From the C++ 17 Standard (5.13.5 String literals)来自 C++ 17 标准(5.13.5 字符串文字)

8 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. 8 普通字符串文字和 UTF-8 字符串文字也称为窄字符串文字。 A narrow string literal has type “array of n const char” , where n is the size of the string as defined below, and has static storage duration (6.7)窄字符串文字的类型为“array of n const char” ,其中 n 是字符串的大小,定义如下,并且具有 static 存储持续时间 (6.7)

So in C++ you have to write所以在 C++ 你必须写

const char *Test = "Hey";

Nevertheless though in C string literals have types of non-constant character arrays you may not change string literals.尽管如此,尽管在 C 中,字符串文字具有非常量字符 arrays 的类型,但您可能不会更改字符串文字。 Any attempt to change a string literal results in undefined behavior.任何更改字符串文字的尝试都会导致未定义的行为。

From the C Standard (6.4.5 String literals)来自 C 标准(6.4.5 字符串文字)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. 7 不确定这些 arrays 是否不同,只要它们的元素具有适当的值。 If the program attempts to modify such an array, the behavior is undefined.如果程序尝试修改这样的数组,则行为未定义。

As for your code snippets then you should at least write至于您的代码片段,那么您至少应该编写

In C在 C

char* Test = malloc( 4 * sizeof( cha));
strcpy( Test, "Hey" );

//...

free( Test );

on C++在 C++

char* Test = new char[4];
std::strcpy( Test, "Hey" );

//...

delete [] Test;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM