Is there a way to return an array from a function?

Ok... So here is a sample function...

1
2
3
4
5
char* func()
{
      arr[] = "Hello world!";
      return arr;
}


Is that possible? If not, please tell me how to accomplish that?
Last edited on
Ok... I see that is valid... But the function just returns H... :(
You must be getting what I am trying to do... Please direct me how...
It returns a pointer to the first element of the array. The rest is up to you.
You cannot return raw arrays from a function. You can, however return a pointer to the first element of an array - that array cannot be a local one, as it would be destroyed when the function exits.

The proper way is to return a string:
1
2
3
4
string func()
{
  return "Hello world!";
}


Or a vector for other types.
How does that even compile?
It's not safe to return a static array from a function, as the array is destructed as soon as the function returns.
Instead, use dynamically allocated array, or std::string.
I just re-compiled it... It's working without any changes... I am not sure what is it doing, nor am I sure why the array is not being destructed... Here is the actual full code... It is returning something, but it is not what I desire... I want to generate a random hash of 15 char, it is returning 7 char... Also, I want the hash to be all alphabets, but it is returning some non-alpha chars anyway. Please take the time to have a thorough look and let me know what would be the "proper" and "professional" way to do it... Thank you...

CODE:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <cstdlib>
#include <ctime>
#ifndef NULL
#define NULL 0
#endif
using namespace std;

char* generateHash(int numBytes);
int main(int *argc, char *argv[])
{
    cout<<generateHash(15)<<endl;
    return 0;
}

char* generateHash(int numBytes)
{
    srand(time(NULL));
    char buffer[numBytes];
    for (int i=0; i<=numBytes; i++)
    {
        buffer[i] = rand() % 90 + 65; // From 65 to 90: only alphabets
    }
    return buffer;
}


My O/P

☺ëPÖ╕sD
Last edited on
Your array is deallocated at the end of the function. You can't return auto arrays. You'll need to allocate them dynamically or use some sort of container
eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
char* generateHash(int numBytes)
{
    //...
    char *buffer = new char [numBytes]; // allocate the array
    //...
    return buffer;
}

int main(int *argc, char *argv[])
{
    char *p = generateHash(15);
    cout << p <<endl; // remember that cout << p ends when it finds a zero character
    delete[] p; // free the array
    return 0;
}

1- I am not sure I have the concept of allocation and de-allocation of pointers... See, this is the "Beginners" section... :)

2- I edited the code and re-executed it... It shows the same O/P, this time a little bit more gibberish.
Ed^êJ|ÄÆ]uztvngmíl┌Ö ÿ


3- I re-edited the code and turned all the chars to ints (except the one in arguments of main)... This showed me (I think) what was running behind the char mask... And the output looks to me like an address in memory (thanks to Embedded-Systems classed :P)... So, I think it is printing the memory address only. Or maybe it is printing the memory address only when it has been explicitly told to deal with it as an int... I dunno. I can't think as deep as you. I aspire to. So enlighten me, por favor.

Thanks a lot.
1. Pointers and dynamic memory management belongs to the basics, though. Read this:
http://www.cplusplus.com/doc/tutorial/dynamic/

2. Post the new code.

3. When trying to print a char pointer, it is interpreted as a null-terminated char array (i.e. a C string).
For an int pointer, the address is printed. So you'll have to print each element manually.
Few things to note:
for (int i=0; i<=numBytes; i++) if the size of the array is numBytes this will overflow ( Use < instead of <= )
buffer[i] = rand() % 90 + 65; generates numbers from 65 to 155 ( 65 + 90 )
You never give the terminator to your string ( the zero char ).

Enlightening links:
http://www.cplusplus.com/doc/tutorial/ntcs/
http://www.cplusplus.com/doc/tutorial/dynamic/
http://www.cplusplus.com/reference/string/string/
@Athar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cstdlib>
#include <ctime>
#ifndef NULL
#define NULL 0
#endif
using namespace std;

int* generateHash(int numBytes);
int main(int *argc, char *argv[])
{
    char *p = generateHash(15);
    cout << p <<endl;
    delete[] p;
    return 0;
}

int* generateHash(int numBytes)
{
    srand(time(NULL));
    int *buffer = new int [numBytes];
    for (int i=0; i<=numBytes; i++)
    {
        buffer[i] = rand() % 90 + 65; // From 65 to 90: only alphabets
    }
    return buffer;
}


By the way, from "3-" I get it why address of only the first element is being printed.
Last edited on
@Bazzy

So kind of you to point out... Corrected the errors, but it is still printing way lot more than 15 chars and some of them gibberish.

From my classes about 8086-debug I remember that some memory locations already have values. I think since the cout statement in main() keeps printing until it encounters a NULL character, it is going on and printing the non-NULL values it encounters even after the desired segment of memory addresses has ended. Is that so?
Remember the string terminating character. The only way you have to tell cout << that your C string is ended is with a zero-character
Wouldn't there be a more flexible way, like iterating the pointer to only a +15 the starting value, manually?
That would require everything that used a C-style string to know the size somehow. If you want a string that knows it's size, just use the C++ std::string.
buffer[i] = rand() % 90 + 65; // From 65 to 90: only alphabets

.... wrong.
array packed into structure, C-style
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

#include <stdio.h>
#include <stdlib.h>

#define MAXARRAY 1000

struct array {
    int arr[MAXARRAY];
};

struct array func(void);

int main(void) /* ANSI C89 */
{
    struct array t = func();
    int i;
    
    for (i = 0; i < 5; i++)
        printf("%d" "\n", t.arr[i]);
    
    return EXIT_SUCCESS;
}

struct array func(void)
{
    struct array a = { { 1, 2, 3, 4, 5 } };
    
    return a;
}
Topic archived. No new replies allowed.