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 :)

Recommended Answers

All 3 Replies

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

Member Avatar for MonsieurPointer

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();
#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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.