0

所以当我写一个函数

void sort (int oldarray[], int length)
{

//imagine there is a function here that runs a loop and finishes with a sorted:

newarray[];
}

如何让 newarray[] 替换主函数中的 oldarray[],如下所示:

int main()
{
int length = 7
int oldarray[length]

//here would be a loop that populates the oldarray

sort(oldarray[], length)

//a loop that prints the newarray[] from the sort or main function
}

仅供参考,这不是家庭作业。我是在自学,所以你不会帮我骗取教授的血汗钱。

4

3 回答 3

0

您不想将 [] 放在您的排序电话中:

sort(oldarray, length)

如果你真的不想从排序函数返回任何东西,而不是传入一个数组,这实际上只是一个指针,你想传入一个指向指针的指针,然后重新分配指针指向的内容(唷)。像这样:

int ** pointer_to_arr = &old; //& gives address of old
sort(pointer_to_arr, length);

排序:

sort(int** arr, int len) {
    //you need to malloc the new array if you don't want it
    //to go away on function return:
    int* new_array = (int*) malloc(len*sizeof(int));
    //... sort here into new_array ...
    *arr = new_array; //set arr to the newly sorted array 
}

您现在可以从 pointer_to_old 访问 new_array:

int* new_array = *pointer_to_arr;
 //... do what you will
//don't forget to release you memory when you're done
free (new_array);
于 2013-03-25T19:07:32.853 回答
0

以下是基于 Aniket 的回答,但经过简化:

#include <stdio.h>
#include <stdlib.h> 

void sort (int *oldarray, int *newarray, int length)
{
    // do your stuff, and put result in newarray
}

int main()
{
    int length = 7;
    int oldarray[length];
    int newarray[length];

    // here would be a loop that populates the oldarray

    sort(oldarray, newarray, length);

    // a loop that prints the newarray from the sort or main function

    return 0;
}
于 2013-03-25T19:18:49.170 回答
0
void sort (int *oldarray, int length, int *newarray, int *newlength)
{

//imagine there is a function here that runs a loop and finishes with a sorted:

//newarray after sorting can be passed to `main` function - even if the function returns void
// also remember to set the `newlength`
}

int main()
{
  int newlength;
  int *newarray = malloc(7 * sizeof(int));
  int length = 7
  int oldarray[length]

  //here would be a loop that populates the oldarray

  sort(oldarray[], length, newarray, &newlength)

  //a loop that prints the newarray[] from the sort or main function
  free(newarray);
  return 0;
}
于 2013-03-25T19:05:26.903 回答