c - 原地反转数组

标签 c arrays

好吧,我已经尝试打印和数组,然后使用另一个数组进行反转,但我正在尝试创建一个 For 循环,它将采用一个数组并反转所有元素,而无需我遍历创建全新数组的过程。

我的 for 循环遇到了一些问题,我不知道从这里去哪里...我使用 i 来获取末尾的元素并将其移动到前面,然后 j 被用作一个计数器来跟踪元素...如果有更简单的方法来做到这一点任何建议将不胜感激。

我是这种编程语言的新手,因此非常感谢任何额外的信息。

#include <stdlib.h>
#include <time.h>

int Random(int Max) {
  return ( rand() % Max)+ 1;
}

void main() {
  const int len = 8;
  int a[len];
  int i;
  int j = 0;
  Randomize() ;

  srand(time(0));
  //Fill the Array
  for (i = 0; i < len; ++i) {
    a[i] = rand() % 100;
  }

  //Print the array after filled
  for (i = 0; i < len; ++i) {
    printf("%d ", a[i]);
  }
  printf("\n");
  getchar();

  //Reversing the array in place.
  for (i = a[len] -1; i >= 0, --i;) {
    a[i] = a[j];
    printf("%d ", a[j]);
    j++;
  }


}

最佳答案

while 循环可能更容易概念化。可以将其视为从两端开始并交换两个元素,直到到达中间。

  i = len - 1;
  j = 0;
  while(i > j)
  {
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
    i--;
    j++;
  }

  //Output contents of now-reversed array.
  for(i = 0; i < len; i++)
    printf("%d ", a[i])

关于c - 原地反转数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54736896/

相关文章:

c++ - 为什么将字符串文字传递给 char* 参数有时只是编译器错误?

ruby-on-rails - 使用其他数组的第一个元素构建和排序数组

c++ - 在 return 语句中将指针强制转换为固定大小的数组

arrays - 试图从数组中求和

带有重音符号的 php 数组排序

C 服务器不接受任何客户端

c - 当从字符串文字初始化 char 数组时会发生什么?

javascript - NPAPI 插件,从网页中删除Child 会导致 Firefox4 和 Chrome 崩溃

c - 在一个头文件中定义结构并在另一个头文件中使用它时出现结构错误

PHP数组映射