C++ 使用字符指针和字符数组的区别

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

Difference between using character pointers and character arrays

c++cpointerscharacter

提问by halluc1nati0n

Basic question.

基本问题。

char new_str[]="";

char * newstr;

If I have to concatenate some data into it or use string functions like strcat/substr/strcpy, what's the difference between the two?

如果我必须将一些数据连接到其中或使用 strcat/substr/strcpy 之类的字符串函数,那么两者之间有什么区别?

I understand I have to allocate memory to the char * approach (Line #2). I'm not really sure how though.

我知道我必须为 char * 方法(第 2 行)分配内存。我不确定如何。

And const char * and string literals are the same?

而 const char * 和字符串文字是一样的吗?

I need to know more on this. Can someone point to some nice exhaustive content/material?

我需要了解更多这方面的信息。有人可以指出一些很好的详尽内容/材料吗?

采纳答案by Justin Samuel

Please go through this articlebelow:

请阅读下面的这篇文章

Also see in case of array of char like in your case, char new_str[] then the new_str will alwayspoint to the base of the array. The pointer in itself can't be incremented. Yes you can use subscripts to access the next char in array eg: new_str[3];

另请参阅在您的情况下,char 数组的情况下, char new_str[] 那么 new_str 将始终指向数组的基数。指针本身不能递增。是的,您可以使用下标访问数组中的下一个字符,例如:new_str[3];

But in case of pointer to char, the pointer can be incremented new_str++to fetch you the next character in the array.

但是在指向 char 的指针的情况下,指针可以递增new_str++以获取数组中的下一个字符。

Also I would suggest this articlefor more clarity.

此外,我建议这篇文章更清晰。

回答by t0mm13b

The excellent source to clear up the confusion is Peter Van der Linden, Expert C Programming, Deep C secrets - that arrays and pointers are not the same is how they are addressed in memory.

消除混淆的最佳来源是 Peter Van der Linden,专家 C 编程,Deep C 的秘密——数组和指针在内存中的寻址方式不同。

With an array,

用数组,

char new_str[];
编译器给了 new_str 一个在编译和运行时都知道的内存地址,例如 0x1234,因此 new_str 的索引很简单,使用[][]. 例如new_str[4]new_str[4],在运行时,代码选择所在位置的地址new_strnew_str,例如 0x1234(即物理内存中的地址)。通过[4][4]向其添加索引说明符0x1234 + 0x4,然后可以检索该值。

Whereas, with a pointer, the compiler gives the symbol

而使用指针,编译器会给出符号

char *newstr
一个地址,例如 0x9876,但在运行时,使用的地址是一种间接寻址方案。假设 newstr 是 malloc'd
newstr = malloc(10);
,发生的事情是,每次在代码中引用使用newstr,因为newstr的地址是编译器知道的,即0x9876,但是newstr指向的是可变的。在运行时,代码从物理内存 0x9876(即 newstr)中获取数据,但在该地址是另一个内存地址(因为我们对其进行了 malloc),例如 0x8765 在这里,代码从该内存地址获取数据malloc 分配给newstr,即0x8765。

The char new_str[]and char *newstrare used interchangeably, since an zeroth element index of the array decays into a pointerand that explains why you could newstr[5]or *(newstr + 5)Notice how the pointer expression is used even though we have declared char *newstr, hence

char new_str[]char *newstr可以互换使用,因为一个数组衰变零个元素的索引为指针,并且解释了为什么你能newstr[5]*(newstr + 5)注意如何指针表达式使用的,即使我们已经宣布char *newstr,因此

*(new_str + 1) = *newstr;
或者
*(new_str + 1) = newstr[1];

In summary, the real difference between the two is how they are accessed in memory.

总之,两者之间真正的区别在于它们在内存中的访问方式。

Get the book and read it and live it and breathe it. Its a brilliant book! :)

拿起这本书,阅读它,生活和呼吸它。它是一本精彩的书!:)

回答by wallyk

This is a character array:

这是一个字符数组:

char  buf [1000];

So, for example, this makes no sense:

因此,例如,这没有任何意义:

buf = &some_other_buf;

This is because buf, though it has characteristics of type pointer, it is already pointing to the only place that makes sense for it.

这是因为buf,虽然它具有类型指针的特性,但它已经指向了唯一对它有意义的地方。

char *ptr;

On the other hand, ptris only a pointer, and may point somewhere. Most often, it's something like this:

另一方面,ptr只是一个指针,并且可能指向某处。大多数情况下,它是这样的:

ptr = buf;              // #1:  point to the beginning of buf, same as &buf[0]

or maybe this:

或者这个:

ptr = malloc (1000);    // #2:  allocate heap and point to it

or:

或者:

ptr = "abcdefghijklmn"; // #3:  string constant

For all of these, *ptr can be written to—except the third case where some compiling environment define string constants to be unwritable.

对于所有这些,*ptr 都可以写入——除了某些编译环境将字符串常量定义为不可写的第三种情况。

*ptr++ = 'h';          // writes into #1: buf[0], #2: first byte of heap, or
                       //             #3 overwrites "a"
strcpy (ptr, "ello");  // finishes writing hello and adds a NUL

回答by Michael Krelin - hacker

The difference is that one is a pointer, the other is an array. You can, for instance, sizeof() array. You may be interested in peeking here

区别在于一个是指针,另一个是数组。例如,您可以使用 sizeof() 数组。你可能有兴趣看这里

回答by Alex Budovski

The type of the first is char[1], the second is char *. Different types.

第一个的类型是char[1],第二个是char *。不同种类。

Allocate memory for the latter with mallocin C, or newin C++.

使用mallocC 或newC++为后者分配内存。

char foo[] = "Bar";  // Allocates 4 bytes and fills them with
                     // 'B', 'a', 'r', '
char *foo = "Bar";
'.

The size here is implied from the initializer string.

这里的大小是从初始化字符串中隐含的。

The contents of fooare mutable. You can change foo[i]for example where i= 0..3.

的内容foo是可变的。foo[i]例如,您可以更改where i= 0..3。

OTOH if you do:

OTOH,如果你这样做:

foo[i] = 'X';  // is now undefined.

The compiler now allocates a static string "Bar" in readonly memory and cannot be modified.

编译器现在在只读内存中分配一个静态字符串“Bar”并且不能修改。

char new_str[] = "";

回答by paxdiablo

If you're using C++ as your tags indicate, you really should be using the C++ strings, not the C chararrays.

如果您按照标签指示使用 C++,那么您确实应该使用 C++ 字符串,而不是 Cchar数组。

The stringtype makes manipulating strings a lot easier.

string类型使操作字符串变得更加容易。

If you're stuck with chararrays for some reason, the line:

如果你char因为某种原因被数组卡住了,那行:

char *new_str = "";

allocates 1 byte of space and puts a null terminator character into it. It's subtly different from:

分配 1 个字节的空间并将空终止符放入其中。它与以下内容略有不同:

char *new_str;

since that may give you a reference to non-writable memory. The statement:

因为这可能会给你一个不可写内存的引用。该声明:

char *new_str = malloc (100); // (remember that this has to be freed) or
char new_str[100];

on its own gives you a pointer but nothing that it points to. It can also have a random value if it's local to a function.

它自己给你一个指针,但它没有指向。如果它是函数的局部值,它也可以有一个随机值。

What people tend to do (in C rather than C++) is to do something like:

人们倾向于做的事情(在 C 而不是 C++ 中)是做这样的事情:

char new_str[]="abcd";  

to get enough space.

以获得足够的空间。

If you use the str...functions, you're basically responsible for ensuring that you have enough space in the chararray, lest you get all sorts of weird and wonderful practice at debugging code. If you use real C++ strings, a lot of the grunt work is done for you.

如果你使用这些str...函数,你基本上负责确保char数组中有足够的空间,以免你在调试代码时得到各种奇怪而美妙的练习。如果您使用真正的 C++ 字符串,那么很多繁重的工作都已为您完成。

回答by Mohit

char *new_str="abcd";  

This specifies an array of characters (a string) of size 5 bytes (one byte for each character plus one for the null terminator). So it stores the string 'abcd' in memory and we can access this string using the variable new_str.

这指定了一个大小为 5 个字节的字符数组(一个字符串)(每个字符一个字节加上一个空终止符)。所以它将字符串 'abcd' 存储在内存中,我们可以使用变量 new_str 访问这个字符串。

// With char array, "hello" is allocated on stack
char s[] = "hello";

// With char pointer, "hello" is stored in the read-only data segment in C++'s memory layout.
char *s = "hello";

// To allocate a string on heap, malloc 6 bytes, due to a NUL byte in the end
char *s = malloc(6);
s = "hello";

This specifies a string 'abcd' is stored somewhere in the memory and the pointer new_str points to the first character of that string.

这指定了一个字符串 'abcd' 存储在内存中的某处,指针 new_str 指向该字符串的第一个字符。

回答by chenlian

To differentiate them in the memory allocation side:

在内存分配方面区分它们:

##代码##

回答by jilles de wit

If you're in c++ why not use std::stringfor all your string needs? Especially anything dealing with concatenation. This will save you from a lot of problems.

如果您使用的是 C++,为什么不使用std::string来满足您所有的字符串需求?尤其是任何处理串联的东西。这将使您免于很多问题。