所以当我写一个函数
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
}
仅供参考,这不是作业。我在教自己,所以你没有帮我欺骗教授用他们辛苦赚来的钱。
答案 0 :(得分: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;
}
答案 1 :(得分:0)
你不想把[]打电话给你排序:
sort(oldarray, length)
如果你真的不想从sort函数返回任何东西而不是传入一个数组,这实际上只是一个指针,你想传入指向指针的指针,然后重新指定指针指向的内容到(phew)。像这样:
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);
答案 2 :(得分: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;
}