*使用指针反转数组的计数器*不起作用

时间:2015-01-19 10:52:34

标签: c arrays

#include<stdio.h>

int main() {

int i;

int vector[5]={6,17,28,39,410},*r;  //variables declaration
r=(int*)&vector;            //pointer declaration


for (i = 0; i<5;i++){           //print the array in using a loop
printf("%d ",vector[i]);
}

printf("\n\n");

for(i=0;i<5;i++){           //print the array in reverse order using a loop
vector[i] = *(r+4-i);           //it should be from the last to the first but it prints it 
    printf("%d ",vector[i]);    //differently, see below
}

return 0;}

应该是:

6 17 28 39 410
410 39 28 17 6

但结果是:

6 17 28 39 410
410 39 28 39 410

最后两个应该是17 6

3 个答案:

答案 0 :(得分:4)

在阅读之前,您正在覆盖您尝试阅读的数据。

只需写出代码手动执行的步骤,您就会看到它。

要进行原位反转,必须交换值,以避免覆盖。

另请注意,在适当的上下文中,数组的名称将计算为指向第一个参数的指针。所以这个:

r=(int*)&vector;

很多更好地写成:

r = vector;

你应该真的避免演员阵容,你的演员表是完全没必要的。

答案 1 :(得分:1)

试试这个:

#include<stdio.h>

int main() {

int i;

int vector[5]={6,17,28,39,410},*r; //variables declaration
r=(int*)&vector;            //pointer declaration


for (i = 0; i<5;i++){           //print the array in using a loop
printf("%d ",vector[i]);
}

printf("\n\n");

for(i=0;i<5;i++){           //print the array in reverse order using a loop
          //it should be from the last to the first but it prints it 
    printf("%d ",*(r+4-i));    //differently, see below
}
return ( 0 );
}

答案 2 :(得分:0)

在您的代码中,您正在更改前两个值。所以前两步你的阵列 会是这样的。

410 39 28 39 410

继续循环后,它将获得替换值。您可以将替换的值存储在另一个数组中。

for(i=0,j=4;i<j;i++,j--){
            temp=vector[i]; // storing the value in  temporary variable
            vector[i] = r[j]; 
            r[j]=temp; // assigning the value .
    }
    for ( i=0;  i < 5 ; i ++ )
            printf("%d\n",vector[i]);
相关问题