我对将数组赋给指针的理解是指针指向数组的第一个索引,所以当打印出指针时,它应该打印出数组的第一个索引的地址,但是在这种情况下怎么会出现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 0x7fff192f88b0foo数组的地址应该与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 ABCthe 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 0x7fff192f88b0The 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;更多推荐
发布评论