只是试图掌握 C++ 的复杂性,因此我在搞乱字符串和指针。但是,我遇到了一些我不太了解的事情。
首先,我使用的是相同的函数,据我所知,每次都给它相同的参数。我从主函数和另一个函数调用它,并从每个函数中获取略有不同的地址。下面是从内存的某些部分读取数据的函数。
void printDataFromAddressForLength(char* pointer, long length)
{
cout << "\n" << endl;
for (int i=0; i<length; i++)
{
cout << "&pointer: " << &pointer + i << "\tData: " << pointer + i << endl;
}
}
这个函数的目标是在每一行上打印当前地址和值,然后迭代并可以在任何地方使用,做同样的事情——非常简单的函数,没有真正的目的。
这是我在 main() 中的代码
MessageData messageData = returnStruct();
printDataFromAddressForLength(messageData.pChar, messageData.length);
我还从我的 returnStruct() 函数中调用 printDataFromAddressForLength。这段代码可以在下面看到。
// Returns MessageData from function
MessageData returnStruct()
{
static string staticTestString = "Time and time again";
MessageData metaData;
MessageData* pMetaData = &metaData;
pMetaData->pChar = &staticTestString[0];
pMetaData->length = staticTestString.length();
printDataFromAddressForLength(pMetaData->pChar, pMetaData->length);
return metaData;
}
下面的输出来自从内部返回结构调用的 printDataFromAddressForLength() 函数。注:0x0027F* 7 *
&pointer: 0027F7BC Data: Time and time again
&pointer: 0027F7C0 Data: ime and time again
&pointer: 0027F7C4 Data: me and time again
&pointer: 0027F7C8 Data: e and time again
&pointer: 0027F7CC Data: and time again
&pointer: 0027F7D0 Data: and time again
&pointer: 0027F7D4 Data: nd time again
&pointer: 0027F7D8 Data: d time again
&pointer: 0027F7DC Data: time again
&pointer: 0027F7E0 Data: time again
&pointer: 0027F7E4 Data: ime again
&pointer: 0027F7E8 Data: me again
&pointer: 0027F7EC Data: e again
&pointer: 0027F7F0 Data: again
&pointer: 0027F7F4 Data: again
&pointer: 0027F7F8 Data: gain
&pointer: 0027F7FC Data: ain
&pointer: 0027F800 Data: in
&pointer: 0027F804 Data: n
此输出来自 main 本身调用的 printDataFromAddressForLength() 函数。注:0x0027F* 8 *
&pointer: 0027F8BC Data: Time and time again
&pointer: 0027F8C0 Data: ime and time again
&pointer: 0027F8C4 Data: me and time again
&pointer: 0027F8C8 Data: e and time again
&pointer: 0027F8CC Data: and time again
&pointer: 0027F8D0 Data: and time again
&pointer: 0027F8D4 Data: nd time again
&pointer: 0027F8D8 Data: d time again
&pointer: 0027F8DC Data: time again
&pointer: 0027F8E0 Data: time again
&pointer: 0027F8E4 Data: ime again
&pointer: 0027F8E8 Data: me again
&pointer: 0027F8EC Data: e again
&pointer: 0027F8F0 Data: again
&pointer: 0027F8F4 Data: again
&pointer: 0027F8F8 Data: gain
&pointer: 0027F8FC Data: ain
&pointer: 0027F900 Data: in
&pointer: 0027F904 Data: n
据我所知,我首先调用该函数,传入一个指针和长度。
然后我将包含这两个参数的结构返回给 main,并使用我期望的相同参数调用相同的函数,长度显然是相同的,但 pChar 有一个奇怪的地址增量。
将不胜感激任何见解!
干杯