C++ 不推荐将字符串常量转换为 'char*'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8126512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:03:14  来源:igfitidea点击:

deprecated conversion from string constant to 'char*'

c++stringchar

提问by mahmood

Possible Duplicate:
C++ deprecated conversion from string constant to 'char*'

可能的重复:
C++ 已弃用从字符串常量到 'char*' 的转换

I want to pass a string via char* to a function.

我想通过 char* 将字符串传递给函数。

 char *Type = new char[10];
 Type = "Access";  // ERROR

However I get this error:

但是我收到这个错误:

 error: deprecated conversion from string constant to 'char*'

How can I fix that?

我该如何解决?

回答by Baltasarq

If you really want to modify Type:

如果你真的要修改类型:

char *Type = new char[10];
strcpy( Type, "Access" );

If you don't want to modify access:

如果您不想修改访问权限:

const char *Type = "Access";

Please note, that, however, arrays of char in C and in C++ come with a lot of problems. For example, you don't really know if the call to new has been successful, or whether it is going to throw an exception. Also, strcpy() could surpass the limit of 10 chars.

请注意,然而,C 和 C++ 中的 char 数组有很多问题。例如,您并不真正知道对 new 的调用是否成功,或者它是否会抛出异常。此外, strcpy() 可能会超过 10 个字符的限制。

So you can consider, if you want to modify type later:

所以你可以考虑,如果你以后想修改类型:

std::string Type = "Access";

And if you don't want to modify it:

如果你不想修改它:

const std::string Type = "Access";

... the benefit of using std::stringis that it is able to cope with all these issues.

...使用的好处std::string是它能够应付所有这些问题。

回答by Keith Thompson

There are a couple of things going on here.

这里有几件事情正在发生。

char *Type = new char[10];

This create a char*pointer named Typeand initializes it to point to the first element of a newly allocated 10-element array.

这将创建一个char*名为的指针Type并将其初始化为指向新分配的 10 元素数组的第一个元素。

Type = "Access";  // ERROR

This assignment doesn't do what you think it does. It doesn't copy the 6-character string "Access"(7 characters including the terminating '\0') to the array you just created. Instead, it assigns a pointerto the first element of that array into your pointer Type. There are two problems with that.

这个任务并没有像你想象的那样做。它不会将 6 个字符的字符串"Access"(包括终止符在内的 7 个字符'\0')复制到您刚刚创建的数组中。相反,它将指向该数组第一个元素的指针分配给您的 pointer Type。这有两个问题。

First, it clobbers the previous value of Type. That 10-character array you just allocated now has nothing pointing to it; you can no longer access it or even deallocate it. This is a memory leak.

首先,它破坏了 的先前值Type。您刚刚分配的 10 个字符的数组现在没有任何指向它;您无法再访问它,甚至无法释放它。这是内存泄漏。

This isn't what the compiler is complaining about.

这不是编译器所抱怨的。

Second, a string literal creates a statically allocated const array ("statically allocated" meaning it exists for the entire execution of your program). Typeis not declared with a constqualifier. If the compiler allowed you to point Typeto the string "Access", you could use that pointer to (attempt to) modify it:

其次,字符串文字创建一个静态分配的 const 数组(“静态分配”意味着它在程序的整个执行过程中都存在)。 Type未使用const限定符声明。如果编译器允许您指向Typestring "Access",您可以使用该指针来(尝试)修改它:

Type = "Access";
Type[0] = 'a'; // try to change the string to "access"

The purpose of constis to prevent you from modifying, or even attempting to modify, things that are read-only. That's why you're not allowed to assign a non-const pointer value to a const pointer object.

的目的const是防止您修改,甚至试图修改只读的东西。这就是为什么不允许将非常量指针值分配给 const 指针对象的原因。

Since you're programming in C++, you're probably better off using std::string.

由于您使用 C++ 进行编程,因此最好使用std::string.

回答by Rob?

I want to pass a string via char* to a function.

我想通过 char* 将字符串传递给函数。

Here is how you can pass a string via char* to a function (note the required constkeyword in the function signature.)

以下是通过 char* 将字符串传递给函数的方法(注意const函数签名中的必需关键字。)

#include <iostream>
void f(const char* p) {
  std::cout << p << "\n";
}

int main() {
  f("Access");
}

But, what if you are invoking an existing function, and cannot modify its signature?

但是,如果您正在调用现有函数,并且无法修改其签名,该怎么办?

If you have some external guarantee that the function will not write through its argument pointer,

如果您有一些外部保证该函数不会通过其参数指针写入,

#include <iostream>
void f(char* p) {
  std::cout << p << "\n";
}

int main() {
  f(const_cast<char*>("Access"));
}

If, on the other hand, the function might write to the string, then you'll need to allocate space for the string:

另一方面,如果函数可能写入字符串,则您需要为字符串分配空间:

#include <iostream>
void f(char* p) {
  *++p;
  std::cout << p << "\n";
}

int main() {
  // Allocate read-write space on the heap
  char *p = new char[strlen("Access"+1)];
  // Copy string to allocated space
  strcpy(p, "Access");
  f(p);
  delete p;
}

or,

或者,

#include <iostream>
void f(char* p) {
  *++p;
  std::cout << p << "\n";
}

int main() {
  // Allocate read-write space on the stack
  char arr[] = "Access";
  f(arr);
}

But, the best course by far is to avoid the whole pointer mishegas:

但是,到目前为止最好的方法是避免整个指针错误:

#include <iostream>
void f(const std::string& p) {
  std::cout << p << "\n";
}

int main() {
  f("Access");
}

回答by T.E.D.

You've got a basic operations problem here, not a coding issue.

这里有一个基本的操作问题,而不是编码问题。

When you want to change the contents of a C char array, you do not use the assignment operator. That will instead change the value of the underlying pointer. Ick.

当您想更改 C 字符数组的内容时,不要使用赋值运算符。这将改为更改基础指针的值。哎呀。

Instead you are supposed to use the C string library routines. For instance, strcpy (Type, "Access");will copy the string literal "Access" into your character array, with its all-important trailing nul character.

相反,您应该使用 C 字符串库例程。例如,strcpy (Type, "Access");将字符串文字“Access”复制到您的字符数组中,并带有其非常重要的尾随空字符。

If you are using C++ (as your tags indicate), you should probably be using std::stringinstead of arrays of char. Assignment works they way you are expecting there.

如果您使用的是 C++(如您的标签所示),您可能应该使用std::string字符数组而不是字符数组。分配按您期望的方式工作。