Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在2D字符数组中打印[x][y]元素的地址?(c+;+;) chararr[2][6]={“你好”,“foo”}; cout_C++_Arrays_Char - Fatal编程技术网

C++ 如何在2D字符数组中打印[x][y]元素的地址?(c+;+;) chararr[2][6]={“你好”,“foo”}; cout

C++ 如何在2D字符数组中打印[x][y]元素的地址?(c+;+;) chararr[2][6]={“你好”,“foo”}; cout,c++,arrays,char,C++,Arrays,Char,hello中的“ello”和“e”的地址是相同的。数组只是一个连续的内存块,它的地址是它的第一个值的地址,这就是为什么数组“ello”的地址与“e”的地址相同。是的,这是可能的,但只需要绕过IOstream对char*的特殊处理(它假定为C字符串并相应地格式化其输出): cout操作员有一个过载,您是否尝试打印一个裸体的char*?当你没有数组时,问题是一样的强制性问题:为什么你使用二维char数组而不是std::vector?…顺便说一句,你不想显得尖刻,而是建议你可以将问题减少2维,解决方案

hello中的“ello”和“e”的地址是相同的。数组只是一个连续的内存块,它的地址是它的第一个值的地址,这就是为什么数组“ello”的地址与“e”的地址相同。

是的,这是可能的,但只需要绕过IOstream对
char*
的特殊处理(它假定为C字符串并相应地格式化其输出):


cout操作员有一个过载,您是否尝试打印一个裸体的
char*
?当你没有数组时,问题是一样的强制性问题:为什么你使用二维
char
数组而不是
std::vector
?…顺便说一句,你不想显得尖刻,而是建议你可以将问题减少2维,解决方案仍然是一样的。
操作符有一个重载就这样,谢谢!我已经尝试过使用void*,但是没有使用“&”,所以它不起作用。请解释一下我为什么需要“&”?因为您应该知道,使用
str[0]
索引可以获得对
char
的引用,但您不需要这样做:您需要一个指针,而
&
就是这样做的。@EmJov:因为如果您想要一个地址,您需要运算符的地址,或者
&
。可能值得注意的是,内置的
x[i]
*(x+i)
完全相同,因此
&x[i]
相当于
x+i
。但是,
&x[i]
的意图更为明确,并且在重载的
操作符[]
arr[0]
是一个
char*
的情况下也可以工作,因此增加它将前进到数组中的第二个char。“铸造为无效”将为您提供该地址
&arr[0]
是指向
字符[6]
的指针,因此将其递增1将移动到
arr
中下一个
字符[6]
数组的开头。这里是一个游乐场:
char arr[2][6] = { "hello", "foo" };

cout << arr[0] << " or " << *(arr) << endl;// prints "hello"
cout << arr[1] << " or " << *(arr + 1) << endl; // prints "foo"

cout << arr << endl; // prints an address of "hello" (and 'h')
cout << arr + 1 << endl; //prints an address of "foo" (and 'f')

cout << arr[0][1] << endl; // prints 'e'
cout << &arr[0][1] << endl; // prints "ello"
cout << (void*)&arr[0][1] << endl;
//      ^^^^^^^
#include <iostream>

int main()
{
    const char* str = "hi";
    std::cout << &str[0]        << '\n'; // "hi"
    std::cout << (void*)&str[0] << '\n'; // some address
}
std::cout << static_cast<const void*>(&arr[0][1]) << std::endl;