简体   繁体   English

无法通过指针访问数组值

[英]Not able to access array values through a pointer

int *ptrr;
int array[3];
for(int i=3;i>0;--i){
      array[i]=i*100;cout<<array[i]<<" "<< & array[i]<<endl;
}
ptrr=array;
for(int i=3;i>0;--i){
    cout<<*(ptrr+i)<<" ";
}
cout<<endl;
for(int i=3;i>0;--i){
    cout<<ptrr[i]<<" ";
}
cout<<endl;
cout<<ptrr<<" "<<*ptrr<<" "<<*ptrr+1<<*ptrr+2<<endl;

I have a basic question that I am able to access the array elements through a pointer in a loop, but when accessed separately it pops out weird values. 我有一个基本问题,我可以通过循环中的指针访问数组元素,但是当单独访问时,它会弹出怪异的值。 The pointer is same still giving different values. 指针相同,但仍给出不同的值。 What is the problem..? 问题是什么..?

Output: 输出:

300 0x7ffface5538c
200 0x7ffface55388
100 0x7ffface55384
300 200 100 
300 200 100 
0x7ffface55380 -1394257008 -1394257007 -1394257006

Use *(ptrr+1) and *(ptrr+2) . 使用*(ptrr+1)*(ptrr+2) * has higher priority than + . *具有比+高的优先级。

You have two different issues in your code. 您的代码中有两个不同的问题。

First your loop iterator is wrong. 首先,您的循环迭代器是错误的。 Your array is of size 3 (valid indices are 0, 1, 2), so there is no array[3] (this memory location is out of scope). 您的数组大小为3(有效索引为0、1、2),因此没有array [3](此内存位置超出范围)。

you should rewrite your loops like given below 您应该像下面给出的那样重写循环

for(int i=2;i>=0;--i){
      array[i]=i*100;cout<<array[i]<<" "<< & array[i]<<endl;
}

Secondly you should use () in below statement. 其次,您应该在下面的语句中使用()。

cout<<ptrr<<" "<<*ptrr<<" "<<*ptrr+1<<*ptrr+2<<endl;

and rewrite your statement as 并将您的陈述重写为

cout<<ptrr <<" "<<*ptrr<<" "<<*(ptrr+1)<< " " << *(ptrr+2)<<endl;

The syntax *ptrr is perfectly fine but since you had started your loop from i=3 and terminated at i>0 (ie i=1) so array[0] remained uninitialized and garbage value was assigned. * ptrr语法非常好,但是由于您从i = 3开始循环并在i> 0(即i = 1)处终止,因此array [0]仍未初始化,并分配了垃圾值。 But with the initialization in my answer it will work. 但是有了我的答案中的初始化,它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM