【问题标题】:Problem with copying an array to another and not modifying the original array [duplicate]将数组复制到另一个数组而不修改原始数组的问题[重复]
【发布时间】:2020-03-12 19:26:03
【问题描述】:

我遇到了问题。我需要以不同的方式对数组进行排序。问题是,在我第一次排序后,我的原始数组保持排序。我尝试将原始数组复制到另一个数组,但它仍然是排序的。我的代码如下:


void printArray(int ** array, int n){
    int i;
    for(i = 0; i < n; i++){
        printf(" %d ", (*array)[i]);
    }
}

int main(){
    int *array, n, number, i, j;

    printf("\nIntroduce the size of the array:");
    scanf("%d", &n);
    array = (int*)malloc(n * sizeof(int));
    for(i = 0; i < n; i++){
        number = rand() % 1000 + 1;
        array[i] = number;
    }

    printf("\nUnsorted array:");
    printArray(&array, n);

    //bubble sort
    int *array2, aux;
    array2 = array;
    for (i = 0; i < n-1; i++){
        for (j = 0; j < n-1; j++){
            if(array2[j] > array2[j+1]){
                aux = array2[j];
                array2[j] = array2[j+1];
                array2[j+1] = aux;
            }
        }
    }
    printf("\nSorted array:");
    printArray(&array2, n);         

    //The problem is in here, if I print the original array, it's already sorted
    printf("\nUnsorted original array:");
    printArray(&array, n);

}

【问题讨论】:

  • array2 = array; 这不会复制数组。这复制了一个指针。指针不是数组。
  • 是的,我有需要用指针来完成的指令,我真的不知道该怎么做。

标签: c sorting


【解决方案1】:

看,你实际上只创建了一个数组。最初,您使用指针变量“array”来指向该数组的基地址。 然后通过这样做,

array2 = array;

您将数组的基地址(存储在指针变量“array”中)复制到指针变量“array2”,并使用此“array2”指针变量对原始(也是唯一的)数组进行排序。

要同时拥有已排序和未排序的数组,您需要复制原始数组,然后对其中任何一个进行排序。 创建原始数组的副本:

int *newArray=(int*)malloc(sizeof(int));    // dynamically allocating memory
for(i=0;i<n;i++){
newArray[i]=array[i];              // *(newArray+i)=*(array+i); alternative
}

【讨论】:

    【解决方案2】:

    代替

    array2 = array;
    

    这样做

    array2 = (int*)malloc(n * sizeof(int));
    for(i = 0; i < n; i++){
         array2[i] = array[i];
    }
    

    【讨论】:

      【解决方案3】:

      发生这种情况是因为您只是将另一个指针(数组)变量分配给内存中的同一地址,因此您对初始数组进行了排序。

      你要做的是在排序之前分配内存并复制数组。您可以执行与您的 printArray() 例程非常相似的操作:

      void copyArray(int *old_array, int *new_array, int n){
          int i;
          for(i = 0; i < n; i++){
              new_array[i] = old_array[i];
          }
      }
      

      然后在你的 main() 中你做:

      array2 = (int*)malloc(n * sizeof(int));
      copyArray(array, array2, n);
      

      【讨论】:

      • 非常感谢!我尝试了新的内存分配,但没有执行 copyArray 例程。再次感谢。
      猜你喜欢
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      • 2017-09-13
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多