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

时间:2022-12-25 21:42:46

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. When I print out the float array I get Type: Float @ whatAppearsToBeAProperMemoryAddress = correctFloat#.

在我的程序的不同点,我有几乎完全相同的代码,但它不是一个char数组,它是一个浮点数组。当我打印出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[\]^_abcdefghijklmnopqrstuvwxyz{|}~??????????????????

然而,虽然字符是正确的,但地址似乎不是。的地址char数组是这样的:?./0123456789 <=> @ 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 ++上的第一次破解。

1 个解决方案

#1


2  

Because &charArray[i] is still a char* pointing to the ith character of the string. So it is used as a whole string. Try to cast as this:

因为&charArray [i]仍然是指向字符串的第i个字符的char *。所以它被用作整个字符串。试着像这样投:

(void*)&charArray[i]

that is the same as:

这与:

(void*)(charArray+i);

#1


2  

Because &charArray[i] is still a char* pointing to the ith character of the string. So it is used as a whole string. Try to cast as this:

因为&charArray [i]仍然是指向字符串的第i个字符的char *。所以它被用作整个字符串。试着像这样投:

(void*)&charArray[i]

that is the same as:

这与:

(void*)(charArray+i);