简体   繁体   中英

difference between c and c++ char pointers

In C this works totally fine:

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

Meanwhile in Cpp it throws me this error:

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

a value of type "const char *" cannot be assigned to an entity of type "char *"

What is the difference between these two and why is a pointer in Cpp alsways a const and cant be modified later?

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. As a result the address of the allocated memory is;lost.

In C++ opposite to C string literals have types of constant character arrays.

From the C++ 17 Standard (5.13.5 String literals)

8 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. 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)

So in C++ you have to write

const char *Test = "Hey";

Nevertheless though in C string literals have types of non-constant character arrays you may not change string literals. Any attempt to change a string literal results in undefined behavior.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. 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

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

//...

free( Test );

on C++

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

//...

delete [] Test;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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