c++ - 如何使用指针更改数组中元素的顺序?

标签 c++ arrays pointers

例如我有一个数组:

int Arr[10]={1,2,3,4,5,6,7,8,9,10};

如何使用指针更改其元素顺序以接收以下数组:

Arr={10,9,8,7,6,5,4,3,2,1}

to change the order odd and even using a pointer I've found this:
But I need only to reverse an array (without replacing odd and even)
#include <iostream>
using namespace std;
int main (const int& Argc, const char* Argv[]){

const int Nelem=10;
int Arr[]={1,2,3,4,5,6,7,8,9,10};
int *begAr=&Arr[0];
int *endAr=&Arr[Nelem];
int *itrAr=begAr;
int *tmpValAr=new int(0);
cout<<"Before\t1 2 3 4 5 6 7 8 9 10"<<endl;
while(itrAr<endAr){
*tmpValAr=*itrAr;
*itrAr=*(itrAr+1);
*(itrAr+1)=*tmpValAr;
itrAr+=2;
}
cout<<"After\t";
for(int i=0; i<Nelem; ++i)cout<<Arr[i]<<" ";
cout<<endl;
system("pause");
return 0;
}  

最佳答案

好的,使用指针反转数组的 C 风格方法?这应该不难理解。这是一种方法:

int main ( void )
{
    int i,//temp var
        arr[10]= {1,2,3,4,5,6,7,8,9,10};//the array
    int *start = &arr[0],//pointer to the start of the array
        *end = &arr[9];//pointer to the last elem in array
    //print out current arr values
    for (i=0;i<10;++i)
        printf("arr[%d] = %d\n", i, arr[i]);
    do
    {//simple loop
        i = *start;//assign whatever start points to to i
        *start = *end;//assign value of *end to *start
        *end = i;//assign initial value of *start (stored in i) to *end
    } while ( ++start < --end);//make sure start is < end, increment start and decrement end
    //check output:
    for (i=0;i<10;++i)
        printf("arr[%d] = %d\n", i, arr[i]);
    return 0;
}

如你所见here ,这会很好地反转数组。

关于c++ - 如何使用指针更改数组中元素的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24231793/

相关文章:

c++ - CMake 链接不正确?

c++ - 从函数访问类

C++ 文件 I/O 仅在 IDE 中运行时有效(Visual C++ Express 2010)

C 初学者 - 数组和指针

c - 反转指向数组的指针

c++ - 左移位和丢弃位

arrays - 一维 “Square”数组中的旋转对称索引

javascript - 如何使用一个数组元素作为另一个数组的索引

c - 如何返回指向缓冲区中位置的指针?

c++ - 类型不匹配