从包含地址字符串元素的指针数组中获取字符串元素的地址

Getting the address of a string element from a pointer array which contains pointer arrays which contain the address string elements

'ptrArrMain'是一个指针数组,包含两个指针数组(ptrArr1和ptrArr2)。我有一个字符串 ab = "ab"。 ab[1]的地址(即'b'的地址)存储在元素ptrArr1[1]中。 ptrArr1[0](即'a'的地址)被分配给ptrArrMain[0]。

如何仅使用 ptrArrMain 数组获取 ab[1] 的地址?我不想使用任何 STL 或预编码函数。我做这个练习是为了加强我对指针的理解。谢谢。

int main()
{

    string ab = "ab";
    string cd = "cd";

    char **ptrArrMain = new char*[2];
    char **ptrArr1 = new char*[ab.length()];
    char **ptrArr2 = new char*[cd.length()];

    ptrArr1[0] = &ab[0];
    ptrArr1[1] = &ab[1];

    ptrArr2[0] = &cd[0];
    ptrArr2[1] = &cd[1];

    ptrArrMain[0] = ptrArr1[0];
    ptrArrMain[1] = ptrArr2[0];

    cout << &ab[1] << endl;

    //  TODO
    //  Get the address of ab[1] using 'ptrArrMain'. 
    //  Do not use any other array.*/

}

我想这应该是可以的,因为ptrArrMain[0]包含了"ab"的第一个元素的地址。有了 "ab" 的第一个元素的地址,我应该能够通过递增(或其他方式)在 ptrArrMain[0] 中的 ab[0] 的地址来获得 ab[1] 的地址。

当我 运行 你的当前代码,使用 using namespace std 指令,并导入 iostreamstring 标准库时,我得到以下结果:

 > g++ test.cpp -o test
 > ./test
 b

这是为什么?如果您查看代码,您会注意到 ab 的类型为 std::string (which is a standard library type). In the documentation we find that using the [] operator on a string is actually an overloaded operation (ie. it calls a method), which returns a reference to a char. If you attempt to get the address of the reference, you get the reference itself,这就是打印 b 的原因。

如果你想获取底层字符串的地址,你应该使用 C-style strings aka character arrays. You can then access the underlying arrays using array subscripts or pointer arithmetic

    char ab[3] = "ab";
char cd[3] = "cd";

char **ptrArrMain = new char*[2];
char **ptrArr1 = new char*[strlen(ab)];
char **ptrArr2 = new char*[strlen(cd)];

ptrArr1[0] = &ab[0];
ptrArr1[1] = &ab[1];

ptrArr2[0] = &cd[0];
ptrArr2[1] = &cd[1];

ptrArrMain[0] = ptrArr1[0];
ptrArrMain[1] = ptrArr2[0];


cout << (void *)&ab[1]  << endl;
cout << (void *)(ptrArrMain[0] + 1) << endl;
cout << (void *)(*ptrArrMain + sizeof(char)) << endl;

这将输出3个相同的内存地址。

您还应注意将字符串地址打印为 cout will interpret them as strings themselves