指向数组c ++的指针(pointer to array c++)

编程入门 行业动态 更新时间:2024-10-22 17:17:52
指向数组c ++的指针(pointer to array c++)

我对将数组赋给指针的理解是指针指向数组的第一个索引,所以当打印出指针时,它应该打印出数组的第一个索引的地址,但是在这种情况下怎么会出现cout打印出整个数组的值? 即使我明确表示我想要第一个索引的地址

char foo[] = {'A','B','C','\0'}; char* p = foo; char* q = &(foo[0]); cout <<"from p: " << p << endl; cout << "from q: " << q << " " << &(foo[0]) << endl; //output from p: ABC from q: ABC ABC

第二个问题是我看到这两行之间的区别在于一个是指向char的指针数组,另一个是指向char数组的指针,这是正确的吗? 括号是必要的吗?

char* bar1[4]; char (*bar2)[4] = &foo; cout << "address of foo is " << bar2 << endl; //output address of foo is 0x7fff192f88b0

foo数组的地址应该与A的地址相同,对吧? 如何打印出A的地址? 因为我没有这样做。 非常感谢你

My understanding about assigning an array to a pointer is that the pointer is pointing at the first index of the array, so when printout the pointer, it should print out the address of the first index of the array, but how come in this case the cout printed out the value of the whole array? even though I explicitly indicated that I wanted the address of the first index

char foo[] = {'A','B','C','\0'}; char* p = foo; char* q = &(foo[0]); cout <<"from p: " << p << endl; cout << "from q: " << q << " " << &(foo[0]) << endl; //output from p: ABC from q: ABC ABC

the second question is that I see the difference between those two lines is that one is an array of pointer to char, the other is a pointer to a char array, is that correct? is the parenthesis necessary?

char* bar1[4]; char (*bar2)[4] = &foo; cout << "address of foo is " << bar2 << endl; //output address of foo is 0x7fff192f88b0

The address of the foo array should be the same as the address of A, right? How do I printout the address of A? since I failed to do so. Thank you very much

最满意答案

<<具有const char *的专用重载,因为这是C风格的字符串。 尝试这个:

cout << static_cast<const void *>(bar2) << endl;

<< has a dedicated overload for const char *, because that's what a C-style string is. Try this:

cout << static_cast<const void *>(bar2) << endl;

更多推荐

本文发布于:2023-07-07 21:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1068525.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   指针   array   pointer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!