简体   繁体   English

如何在c ++中获取指向char []的指针的内存地址

[英]How to get the memory address of a pointer to a char[] in c++

Full disclosure: This is homework. 完全披露:这是作业。 I'm just really confused about one part. 我只是对一部分感到困惑。 I have this code in a c++ program: 我在c ++程序中有这个代码:

char * charArray = new char[100];

//fill charArray 
char c = '.';
for(int i=0; i<100; i++)
{
    charArray[i] = c;
    c = c + 1;
}
cout <<"Char Array: " << endl;
for(int i=0; i<100; i++)
{
    cout << "Type: Char @ " << &charArray[i] << " = " << charArray[i] <<endl;
}

At a different point in my program I have pretty much the exact same code but instead of a char array it is a float array. 在我的程序中的不同点我几乎完全相同的代码,但它不是一个char数组,它是一个浮点数组。 When I print out the float array I get Type: Float @ whatAppearsToBeAProperMemoryAddress = correctFloat#. 当我打印出float数组时,我得到Type:Float @ whatAppearsToBeAProperMemoryAddress = correctFloat#。

However although the chars are correct the address don't appear to be. 然而,虽然字符是正确的,但地址似乎不是。 The address for the char array go like this: ./0123456789<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_ abcdefghijklmnopqrstuvwxyz{|}~?????????????????? /0123456789<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_ 地址为char数组是这样的:./0123456789<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_ abcdefghijklmnopqrstuvwxyz{|}~?????????????????? /0123456789<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_ abcdefghijklmnopqrstuvwxyz{|}~?????????????????? /0123456789<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_ abcdefghijklmnopqrstuvwxyz{|}~?????????????????? abcdefghijklmnopqrstuvwxyz{|}~?????????????????? /0123456789<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_ ABCDEFGHIJKLMNOPQRSTUVWXYZ {|}〜??????????????????

.... all the way to ?? ....一直到?? ?

So obviously instead of getting the address I am getting varying degrees of what should be the contents of the array. 所以很明显,不是获取地址,我得到不同程度的数组内容。 I am very confused and any pointers would be appreciated. 我很困惑,任何指针都会受到赞赏。 This is my first crack at c++. 这是我在c ++上的第一次破解。

Because &charArray[i] is still a char* pointing to the ith character of the string. 因为&charArray[i]仍然是指向字符串的第i个字符的char* So it is used as a whole string. 所以它被用作整个字符串。 Try to cast as this: 试着像这样投:

(void*)&charArray[i]

that is the same as: 这与:

(void*)(charArray+i);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM