C++ 为什么指向 char 数组的指针需要 strcpy 将字符分配给它的数组,而双引号赋值不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1577765/
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-27 20:30:49  来源:igfitidea点击:

Why must a pointer to a char array need strcpy to assign characters to its array and double quotes assignment will not work?

c++arraysstringcharstrcpy

提问by Omar

The first example does not work when you go to delete the pointer. The program either hangs when I add the null terminator or without it I get:

当您删除指针时,第一个示例不起作用。当我添加空终止符或没有它时,程序要么挂起,我得到:

Debug Assertion Failed Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)from Visual Studio 2008

Debug Assertion Failed Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)来自 Visual Studio 2008

//Won't work when deleting pointer:
    char *at = new char [3];
    at = "tw"; //   <-- not sure what's going on here that strcpy does differently
    at[2] = '
char *at = ...;

at = "hello";
'; // <-- causes program to hang delete at; //Works fine when deleting pointer: char *at = new char [3]; strcpy(at,"t"); at[1] = 'w'; at[2] = '
at = "tw";
'; delete at;

So what's going on when I use double quotes instead of strcpy? Both of them will cout the string perfectly and debugger does not show anything different.

那么当我使用双引号而不是 strcpy 时发生了什么?它们都将完美地输出字符串,并且调试器不会显示任何不同。

回答by unwind

When you do

当你做

char *at = new char [3];
//at now contains the address of the memory allocated on the heap


at = "hello";
//at now contains the address of the static string. 
// (and by the way you just created a 3 byte memory leak)


delete[] at; 
//WOOPS!!!! you can't do that because you aren't deleting 
// the original 3 chars anymore which were allocated on the heap!
//Since at contains the string literal's memory address you're 
// trying to delete the string literal.

You're basically overwriting the pointer value (i.e., the address of the memory allocated for you by new[]) with the address of a static constant string. This means that when you later delete thatmemory, you're passing deletea pointer not previously returned by new.

您基本上new[]是用静态常量字符串的地址覆盖指针值(即由 为您分配的内存地址)。这意味着当您稍后删除内存时,您正在传递delete一个以前未由new.

That is a bad thing to be doing.

这是一件坏事。

In C and C++, assignments to pointers typically don't do anything to the memory being pointed at, they change the pointer itself. This might be confusing if you're used to a language where strings are more of "first class citizens".

在 C 和 C++ 中,对指针的赋值通常不会对所指向的内存做任何事情,它们会改变指针本身。如果您习惯于字符串更多是“一等公民”的语言,这可能会令人困惑。

Also, you should use delete[]if you used new[].

此外,delete[]如果您使用new[].

回答by sbi

Because a char*isn't a string. It's just a pointer to some character, with the convention that there might be more characters to follow and that after the last one there is a '\0'.

因为 achar*不是字符串。它只是一个指向某个字符的指针,按照约定可能会有更多的字符要跟随,并且在最后一个字符之后有一个'\0'.

A string literal in C (and thus in C++) like "abc"is just an array of characters, with the compiler silently adding a '\0'. When you assign an array to a pointer, the array silently converts a pointer to the first element. The result is that

C(因此在 C++ 中)中的字符串文字"abc"只是一个字符数组,编译器默默地添加了一个'\0'. 将数组分配给指针时,该数组会默默地将指针转换为指向第一个元素的指针。结果是

char *at = "hello";
at[2] = '
#include <string>

using namespace std;

int main(int argc, char **argv)
{
  string s = "hello";
  s += " world!";

  //s now contains "hello world!"

  s = "goodbye!";

  //Everything is still valid, and s contains "goodbye!"


  //No need to cleanup s. 

  return 0;
}
';

means, the pointer atis assigned the address of the first character in the string literal "tw". By this, it will lose its old value. Since this was the address of a dynamically allocated character array, you are leaking this array.

意味着,指针at被分配了字符串文字中第一个字符的地址"tw"。这样,它将失去其旧价值。由于这是动态分配的字符数组的地址,因此您正在泄漏该数组。

When you later assign to a character in the array atnow points to, you are assigning a new value to some character in the string literal. That's invoking undefined behavior and the program hanging or crashing immediately is probably the best that could happen to you when you do this. (On many platforms you're writing to read-only memory doing so.)

当您稍后分配给at现在指向的数组中的一个字符时,您正在为字符串文字中的某个字符分配一个新值。这会调用未定义的行为,并且程序立即挂起或崩溃可能是您执行此操作时可能发生的最好情况。(在许多平台上,您正在写入只读内存。)

Later you pass atto delete[](and not delete, since you called new[], not new). In doing so, you pass it the address of the string literal, instead of the allocated character array. This will, of course, mess up the heap manager. (VC's runtime library catches this in Debug mode.)

稍后您传递atdelete[](而不是delete,因为您调用了new[],而不是new)。这样做时,您将字符串文字的地址传递给它,而不是分配的字符数组。当然,这会弄乱堆管理器。(VC 的运行时库会在 Debug 模式下捕获它。)

std::strcpy, on the other hand, copies a string character by character from one array to another array. No pointers will be changed, only pieces of memory are copied. The pointer to the target array still points to the target array afterwards, only the data in that array has changed.

std::strcpy,另一方面,将一个字符串逐个字符地从一个数组复制到另一个数组。不会更改指针,只会复制内存片段。之后指向目标数组的指针仍然指向目标数组,只是该数组中的数据发生了变化。

Let me add this: As a beginner in C++, you should use std::string, rather than C strings. That does all the dirty work for you and has sane semantics.

让我补充一点:作为 C++ 的初学者,您应该使用std::string, 而不是 C 字符串。这为您完成了所有肮脏的工作,并且具有合理的语义。

回答by Brian R. Bondy

There are 3 things to understand:

有3件事要理解:

1) char *at;is just a pointer variable.
A pointer variable simply means that it holds a memory address.

1)char *at;只是一个指针变量。
指针变量仅仅意味着它保存了一个内存地址。

2) new char[3]returns the starting address of the memory allocated on the heap.

2)new char[3]返回分配在堆上的内存的起始地址。

3) "hello"returns the address of the string literal.

3)"hello"返回字符串文字的地址。

delete []

A note about modifying read only memory:

关于修改只读内存的注意事项:

Also you should never be modifying a string literal. I.e. this should never be done:

此外,您永远不应该修改字符串文字。即永远不应该这样做:

at = "tw";

The memory for string literals must be read only and if you change it, the results are undefined by the C++ language.

字符串文字的内存必须是只读的,如果更改它,C++ 语言将无法定义结果。

Since you're using C++:

由于您使用的是 C++:

Since you're using C++ please consider using the std::stringtype instead.

由于您使用的是 C++,请考虑改用std::string类型。

at[2] = '
at = "tw"
';

回答by alexkr

Do not forget to use

不要忘记使用

char *at = new char[3];    // 0x1000
at = "tw";                 // 0x2000
at[2] = '
at = "tw";
'; // set char at 0x2002 to 0 delete at; // delete 0x2000 (whoops, didn't allocate that!)

whenever you are allocating something with [].

每当您使用 [] 分配某些内容时。

回答by Patrick

A pointer holds an address. The = operator for a pointer changes the address held.

一个指针保存一个地址。指针的 = 运算符会更改所持有的地址。

char *at = new char [3];
strcpy(at,"t");

Makes at point to the array "tw" (an array created by the compiler to hold the characters tw), it no longer points to the array you created with new. created in the file.

指向数组“tw”(由编译器创建的用于保存字符 tw 的数组),它不再指向您使用 new 创建的数组。在文件中创建。

##代码##

Adds a NULL to the end of the complier array.

将 NULL 添加到编译器数组的末尾。

回答by resolveaswontfix

In your first example you are allocating some memory and pointing to it with the "at" variable. When you do

在您的第一个示例中,您正在分配一些内存并使用“at”变量指向它。当你做

##代码##

you are effectively re-pointing the char * to a constant character string. This causes you to leak memory. When you go on to delete "at" you are attempting to delete stack memory.

您实际上是将 char * 重新指向一个常量字符串。这会导致您泄漏内存。当您继续删除“at”时,您正在尝试删除堆栈内存。

strcpy goes through each character and copies their values to the new memory you allocate. This is also known as a deep copy.

strcpy 遍历每个字符并将它们的值复制到您分配的新内存中。这也称为深拷贝。

回答by KingPong

In the first example, you have caused a memory leak.

在第一个示例中,您造成了内存泄漏。

Your variable atis a pointer to a memory address, not the string itself. When you assign the address of "tw"to the pointer, you have lost the original address that you got with new. atnow points to an address that you did not allocate with new, so you cannot deleteit.

您的变量at是指向内存地址的指针,而不是字符串本身。当您将 的地址分配给"tw"指针时,您已经丢失了使用 获得的原始地址newat现在指向一个你没有分配的地址new,所以你不能分配delete

If you think of pointers as integers, it will probably make more sense. I've assigned arbitrary numbers as addresses for the sake of discussion.

如果您将指针视为整数,它可能会更有意义。为了讨论起见,我指定了任意数字作为地址。

##代码##

回答by pythonic metaphor

In the first example you are chaning the value at, in the second you are changing the value of what at points to. Assigning a char * to a double quoted string assigns it to a static const pointer.

在第一个示例中,您正在更改 at 的值,在第二个示例中,您正在更改 at 指向的值。将 char * 分配给双引号字符串会将其分配给静态常量指针。

In particular, in the first example at now points a different location in memory.

特别是,在第一个示例中,现在指向内存中的不同位置。

回答by Tadeusz Kopec

You mistake two things: making pointer point to something different (this is what assignment does) and copying some data to a place pointed by pointer.

你误会了两件事:使指针指向不同的东西(这就是赋值的作用)和将一些数据复制到指针指向的地方。

##代码##

this code makes atpoint to a literal "tw" created somewhere in read-only memory. Trying to write to it is an undefined behaviour.

此代码at指向在只读内存中某处创建的文字“tw”。尝试写入它是一种未定义的行为。

##代码##

this code allocates memory for three chars and makes atpoint to this part of memory (line 1) and then copies some data to memory pointed by at.

此代码为三个字符分配内存并at指向这部分内存(第 1 行),然后将一些数据复制到at.

And remember, that memory allocated with new[]should be deallocated with delete[], not delete

请记住,分配的内存new[]应该被释放delete[],而不是delete

I advice you to learn more about pointers. This discussioncovers this.

我建议您了解有关指针的更多信息。本次讨论涵盖了这一点。