简体   繁体   English

从void,C返回array []

[英]Returning array[] from void, C

So when I write a function 所以当我写一个函数

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

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

newarray[];
}

How do I get newarray[] to replace oldarray[] in the main function that could look like this: 我如何在主函数中使用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
}

FYI this isn't homework. 仅供参考,这不是功课。 I'm teaching myself, so you aren't helping me cheat a professor out of their hard earned money. 我在自学,所以您不会帮我用他们的辛苦钱骗一位教授。

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;
}

you don't want to put [] on your call to sort: 您不想在通话中加入[]进行排序:

sort(oldarray, length)

If you really don't want to return anything from the sort function instead of passing in an array, which is really just a pointer, you want to pass in a pointer to a pointer and then re-assign what the pointer points to (phew). 如果您真的不想从sort函数返回任何东西,而不是传入实际上只是一个指针的数组,则希望将一个指针传递给一个指针,然后重新分配该指针指向的位置(phew )。 Like so: 像这样:

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

In sort: 排序:

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 
}

You can now access new_array from pointer_to_old: 现在,您可以从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);

Following is based on Aniket's answer, but simplified: 以下内容基于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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM