c++ -- returning an array from function

This is a discussion on c++ -- returning an array from function within the C++ Programming forums, part of the General Programming Boards category; Ok i have a small problem where i have a function that generates an array of characters. However, if i ...

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    14

    c++ -- returning an array from function

    Ok i have a small problem where i have a function that generates an array of characters. However, if i try to return that array i get a mess of errors. I think that i need to use a pointer to do it however, all the examples i saw used integers and did not work for me. This project i am working on is over my head, but that is how i learned all my other programing languages so please understand that my errors may just be newbie errors. Thanks! ~p4plus2~

    ...and if it helps here is the function:
    i know i could combine the separate for loops but i left em apart since its was for a debugging reason and will not be there in my final product.
    This also may not be the best way that i can accomplish what i am doing, but i think it is probably a better learning experience to do it the long way, however feel free to suggest another way to do this so if i make a new version maybe i will try a method suggested.
    Code:
    char start_rubik(){
    	char cube[6][3][3];
    	char color[] = {'b', 'o', 'g', 'r', 'w', 'y'}; 
    	for(int i = 0; i != 6; i++){	
    		for(int b = 0; b != 3; b++){
    			for(int a = 0; a !=3; a++){
    				cube[i][b][a] = color[i];
    			}
    		}
    	}
    	for(int i = 0; i != 6; i++){	
    		for(int b = 0; b != 3; b++){
    			for(int a = 0; a !=3; a++){
    				std::cout << cube[i][b][a];
    			}
    			std::cout << "\n";
    		}
    	}
    	return cube;  //this is that nasty array i can't figure out.
    }
    For anybody who didn't guess, this script (once combined with all its other functions) will be a rubiks cube command line.....as stupid of an idea as that is i think it is a great learning experiance

  2. #2
    Registered Abuser Loic's Avatar
    Join Date
    Mar 2007
    Location
    Sydney
    Posts
    115
    I think I posed the same thread when I signed up to these forums… but, what I ended up doing was passing an array to the function by reference… so something like this

    Code:
    void start_rubik(char cube){
    	char color[] = {'b', 'o', 'g', 'r', 'w', 'y'}; 
    	for(int i = 0; i != 6; i++){	
    		for(int b = 0; b != 3; b++){
    			for(int a = 0; a !=3; a++){
    				cube[i][b][a] = color[i];
    			}
    		}
    	}
    	for(int i = 0; i != 6; i++){	
    		for(int b = 0; b != 3; b++){
    			for(int a = 0; a !=3; a++){
    				std::cout << cube[i][b][a];
    			}
    			std::cout << "\n";
    		}
    	}
    }
    edit: i just found my old thread... and i was told there that arrays are passed by reference automatically... so that should work...
    Last edited by Loic; 08-17-2008 at 09:09 PM.

  3. #3
    Registered User
    Join Date
    Aug 2008
    Posts
    14
    i get the error:
    tutorial.cpp: In function ‘void start_rubik(char)’:
    tutorial.cpp:11: error: invalid types ‘char[int]’ for array subscript
    tutorial.cpp:18: error: invalid types ‘char[int]’ for array subscript
    from g++ when trying to compile like that :|
    lines 11 and 18 are the [i][b][a] lines

    edit:
    after reobserving your code i come to question why would i use cube as an arguement when that should be my result...
    Last edited by p4plus2; 08-17-2008 at 09:21 PM.

  4. #4
    Registered User Kernel Sanders's Avatar
    Join Date
    Aug 2008
    Posts
    61
    The function is returning a single char. To return the array you need to return a char *. Also, you need to dynamically allocate the room for the array with new. Otherwise, when the function ends the array goes out of scope and gets trashed.

  5. #5
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Quote Originally Posted by Loic View Post
    I think I posed the same thread when I signed up to these forums… but, what I ended up doing was passing an array to the function by reference… so something like this

    Code:
    void start_rubik(char cube){
    	char color[] = {'b', 'o', 'g', 'r', 'w', 'y'}; 
    	for(int i = 0; i != 6; i++){	
    		for(int b = 0; b != 3; b++){
    			for(int a = 0; a !=3; a++){
    				cube[i][b][a] = color[i];
    			}
    		}
    	}
    	for(int i = 0; i != 6; i++){	
    		for(int b = 0; b != 3; b++){
    			for(int a = 0; a !=3; a++){
    				std::cout << cube[i][b][a];
    			}
    			std::cout << "\n";
    		}
    	}
    }
    edit: i just found my old thread... and i was told there that arrays are passed by reference automatically... so that should work...
    What array? You're passing a single char by value to the function.
    This is how you pass an array by reference:
    Code:
    void start_rubik( char*** cube )
    or
    void start_rubik( char cube[6][3][3] )

  6. #6
    Registered User
    Join Date
    Aug 2008
    Posts
    14
    @kernel how do i dynamically allocate more room for the array(remember i am a newbie :|)


    @cpjust
    my function made an array IN the function, that funtion was a suggested one i should try and i couldn't make it work(if i understand what you said...) and yes i tried adding [6][3][3] to that version too

    I do not want to add the array as a reference
    Last edited by p4plus2; 08-17-2008 at 09:51 PM.

  7. #7
    Registered User
    Join Date
    Apr 2006
    Posts
    2,032
    You cannot return an array by value. You can return an array by reference, but to do that you must first store the array somewhere.

    Since this is C++, the best way is to instead of using a function, use an object that holds an array inside it, and have those functions that would modify the array directly be methods of that class.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  8. #8
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,183
    @kernel how do i dynamically allocate more room for the array(remember i am a newbie :|)
    use "new" and "delete"

    at this stage, a reference would be a better solution IMHO.

    The problem with returning a pointer to an array allocated on the stack (char asdf[10]) is that the memory is deallocated when the function returns, and you end up accessing random things that happen to be in memory where the array used to be.

  9. #9
    Registered User
    Join Date
    Aug 2008
    Posts
    14
    I have not got to classes yet sadly...I have been trying to get a grasp on lower content first....to an extent i have it all down but pointers keep dragging me down.....i decided to make this script just to practice what i already know....and since other languages like php are able to return arrays and it is written in c++ i just figured it would be possible...

    well thanks for all input i suppose i will trash this scrip(for now untill i am better)


    EDIT:
    would it be possible to write all the contents of the array to a file to use in another function? i don't really know how i would do it.....
    Last edited by p4plus2; 08-17-2008 at 10:04 PM.

  10. #10
    Registered User
    Join Date
    Apr 2006
    Posts
    2,032
    Quote Originally Posted by p4plus2 View Post
    @kernel how do i dynamically allocate more room for the array(remember i am a newbie :|)
    In this case the syntax is:
    Code:
    char (*cube)[3][3]= new char[6][3][3];
    Also the return value would be
    Code:
    char (*start_rubik())[3][3]{
      ...
      return cube;
    }
    Notice that since the return type surrounds the function name and arguements, in exactly the same way that is surrounds the variable name above.

    Or alternatively:
    Code:
    char (&start_rubik())[6][3][3]{
      ...
      return *reinterpret_cast<char(*)[6][3[3]>(cube);
    }
    Here you are returning an array reference. The advantage of this is that the 6 is preserved in the type.
    EDIT: This one requires a cast.

    But you don't want to do that because generally functions are not expected to make the user de-allocate the object as required here.
    Last edited by King Mir; 08-17-2008 at 10:30 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  11. #11
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,699
    >> would it be possible to write all the contents of the array to a file to use in another function? i don't really know how i would do it

    That's possible but laughably slow.

    Do you have a book you can look at? You need to learn about C++ functions and arrays as parameters.

  12. #12
    Registered User Kernel Sanders's Avatar
    Join Date
    Aug 2008
    Posts
    61
    Code:
    char *start_rubik(){
    	char *cube = new char[6*3*3];
    	char color[] = {'b', 'o', 'g', 'r', 'w', 'y'}; 
    	for(int i = 0; i != 6; i++){	
    		for(int b = 0; b != 3; b++){
    			for(int a = 0; a !=3; a++){
    				cube[i][b][a] = color[i];
    			}
    		}
    	}
    	for(int i = 0; i != 6; i++){	
    		for(int b = 0; b != 3; b++){
    			for(int a = 0; a !=3; a++){
    				std::cout << cube[i][b][a];
    			}
    			std::cout << "\n";
    		}
    	}
    	return cube;  //this is that nasty array i can't figure out.
    }
    At some point you need to call delete cube[] (or whatever you store the return value in) to return the memory to the heap

    **EDIT**
    was typing when King Mir posted

  13. #13
    Registered User
    Join Date
    Apr 2006
    Posts
    2,032
    Quote Originally Posted by cpjust View Post
    What array? You're passing a single char by value to the function.
    This is how you pass an array by reference:
    Code:
    void start_rubik( char*** cube )
    or
    void start_rubik( char cube[6][3][3] )
    I'd recommend:

    Code:
    void start_rubik( char (&cube)[6][3][3] )
    So that you cannot pass an array with a different first dimension.

    The char *** version is uses when the array is not in continuous memory; it gets allocated differently than I showed above. In this case I think it makes more sense to use continuous memory.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  14. #14
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Another option is to make the array in the function static. Then you can return it by reference without allocating memory for it. It won't be multi-thread safe, but since you're just starting out, you probably won't be using threads any time soon anyways.

  15. #15
    Registered User
    Join Date
    Aug 2008
    Posts
    14
    Quote Originally Posted by citizen View Post
    >> would it be possible to write all the contents of the array to a file to use in another function? i don't really know how i would do it

    That's possible but laughably slow.

    Do you have a book you can look at? You need to learn about C++ functions and arrays as parameters.
    i do not have a book, just using various internet resources....

    @everybody else i will be looking at your posts, need time to acctually think through and test each one...

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  2. Replies: 6
    Last Post: 11-09-2006, 02:28 AM
  3. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  4. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 09:18 AM
  5. Replies: 6
    Last Post: 10-21-2003, 09:57 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21