c++ function that return array code example
Example 1: c++ function return array
#include <iostream>
#include <ctime>
using namespace std;
int * getRandom( ) {
static int r[10];
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 10; ++i) {
r[i] = rand();
cout << r[i] << endl;
}
return r;
}
int main () {
int *p;
p = getRandom();
for ( int i = 0; i < 10; i++ ) {
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}
Example 2: return array of string in function c++
string* getNames() {
string* names = new string[3];
names[0] = "Simon";
names[1] = "Peter";
names[2] = "Dave";
return names;
}
Example 3: return function in cpp
void printChars(char c, int count) {
for (int i=0; i<count; i++) {
cout << c;
}
return;
}
Example 4: return function in cpp
int max(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}