0

Hey, I need to make a function that returns an array. How would I do so? And how would I make a variable that gets all the values in that function? Thanks, you guys :)

3
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by Moschops
0

Please, help you guys. I need help, so badly.

0

As far as I know you can't return a C-type array (e.g. myarray[100]), but you can return a std::vector, like so:

vector<int> myfunction(void)

Then, once you need the result, you would do something like this:

vector<int> someInts;
someInts = myfunction();
0
#include "stdio.h"
#include "stdlib.h"

int* someFunction(void)
{
  int* array;
  array = (int*)malloc(100 * sizeof(int));
  array[0]=10;
  array[1]=54;
  return array;
};

int main()
{
  int* array = someFunction();
  printf("%i %i", array[0], array[1]);
  free(array);
  return 0;
}

or in C++...

#include <iostream>

int* someFunction()
{
  int* array = new int[100];
  array[0]=10;
  array[1]=54;
  return array;
}

int main()
{
  int* array = someFunction();
  std::cout << array[0] << " " << array[1];
  delete[] array;
  return 0;
}

Edited by Moschops: C and C++ version

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.