字符串类型数组上的指针算术,C ++如何处理? [英] Pointer arithmetic on string type arrays, how does C++ handle this?

查看:71
本文介绍了字符串类型数组上的指针算术,C ++如何处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习有关指针的知识,一个概念困扰着我. 我了解,如果您有一个INT类型的指针(例如'pointer1')指向一个数组,则可以用INTS填充该数组.如果要寻址数组的成员,则可以使用指针,也可以执行pointer1 ++;逐步遍历数组.该程序知道它是一个INT数组,因此它知道以INT大小步进. 但是,如果数组是字符串,该字符串的长度可以变化.当每个元素的长度不同时,如何尝试用++递增,它怎么知道?

I am learning about pointers and one concept is troubling me. I understand that if you have a pointer (e.g.'pointer1') of type INT that points to an array then you can fill that array with INTS. If you want to address a member of the array you can use the pointer and you can do pointer1 ++; to step through the array. The program knows that it is an array of INTs so it knows to step through in INT size steps. But what if the array is of strings whcih can vary in length. How does it know what to do when you try to increment with ++ as each element is a different length?

类似地,当您创建一个字符串向量并使用reserve关键字时,如果字符串长度可以不同,它如何知道要保留多少呢? 这可能确实很明显,但是我无法解决,并且不适合我当前(可能是错误的)关于指针的想法. 谢谢

Similarly, when you create a vector of strings and use the reserve keyword how does it know how much to reserve if strings can be different lengths? This is probably really obvious but I can't work it out and it doesn't fit in with my current (probably wrong) thinking on pointers. Thanks

推荐答案

非常简单.

字符串数组不同于字符串向量.

An array of strings is different from a vector of strings.

字符串数组(C风格的指针)是指向字符数组"char **"的指针的数组.因此,字符串数组中的每个元素的大小都为指针到字符数组",因此它可以毫无问题地逐步遍历字符串数组中的元素.数组中的指针可以指向不同大小的内存块.

An array of strings (C-style pointers) is an array of pointers to an array of characters, "char**". So each element in the array-of-strings is of size "Pointer-to-char-array", so it can step through the elements in the stringarray without a problem. The pointers in the array can point at differently size chunks of memory.

带有字符串向量,它是字符串对象数组(C ++样式).每个字符串对象具有相同的 object 大小,但在某处包含指向内存的指针,该内存实际上存储了字符串的内容.因此,在这种情况下,向量中的元素大小也相同,尽管不同于只是指向字符数组的指针",从而可以进行简单的元素地址计算.

With a vector of strings it is an array of string-objects (C++ style). Each string-object has the same object size, but contains, somewhere, a pointer to a piece of memory where the contents of the string are actually stored. So in this case, the elements in the vector are also identical in size, although different from "just a pointer-to-char-array", allowing simple element-address computation.

这篇关于字符串类型数组上的指针算术,C ++如何处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆