[英]integer arrays and character arrays with pointers
I would really like some help regarding pointers in c++.我真的想要一些关于 c++ 中的指针的帮助。 Take a look at the following code:
看看下面的代码:
int array[3]={4,7,2};
int * a;
a = array;
char Carray[3]={'p','k','\0'};
char * c;
c = Carray;
cout << a << "\n";
cout << c << "\n";
Printing a gives back the address of the first element of the array ie 4 as expected.打印 a 按预期返回数组第一个元素的地址,即 4。
But printing c should have given the address of the first element of Carray ie p but instead it gives the whole string ie 'pk' in this case.但是打印 c 应该给出 Carray 的第一个元素的地址,即 p ,但在这种情况下它给出了整个字符串,即 'pk'。 and we havent used a value operator * here.
我们还没有在这里使用值运算符 *。
It will be very kind if someone can explain this to me如果有人可以向我解释这一点,那就太好了
It is because std::cout
treats char*
as C-style string.这是因为
std::cout
将char*
视为 C 样式字符串。 If you need the address you can try:如果您需要地址,您可以尝试:
std::cout << (void *) c;
you should specify how your variables should be treated during the printout.您应该指定在打印输出期间应如何处理变量。 it's not quite obvious when using streams, so I'd recommend to start from the simple things, namely
printf
:使用流时不是很明显,所以我建议从简单的事情开始,即
printf
:
printf( "%d\n", *a );
printf( "%d\n", a );
printf( "%c\n", *c );
printf( "%s\n", c );
And see what kind of the output you get.看看你得到什么样的 output。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.