Thread: Passing an array as reference to a function?

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    21

    Passing an array as reference to a function?

    Hello everyone... again.
    It's no secret that pointers are really confusing for me, especially pointers to arrays.

    I've been making a little "text adventure" game. So far everything is going great. Except this.

    I need to pass an array of "levels" by reference to a function that initializes them with default settings. I tried a couple of things, but they didn't work at all... Sorry if it's a really newbie question, but pointers hate me.


    This is the function (The first parameter is the array of levels, and as you can see, I didn't declare it right)

    Code:
    void LevelInit(level &levels[], int lv){
    	cout<<"Initializing levels...";
    	for(int i=0; i<(lv+1); i++){
    		*(levels+i)->inicializarlevel();
    	}
    	cout<<" OK"<<endl;
    	cout<<"Loading levels...";
             //To do
    	cout<<" OK"<<endl;
    }


    And this is the call to the function

    Code:
    level nivel[NIVELES];
    LevelInit(nivel, totalniveles);

    Thanks in advance, you always save me!

  2. #2
    Registered User mrafcho001's Avatar
    Join Date
    Jan 2005
    Posts
    483
    Code:
    void Function(int* j)
    {
    ...
    }
    ...
    
    int j[10];
    Function(&j);
    that is how you pass arrays by reference
    My Website
    010000110010101100101011
    Add Color To Your Code!

  3. #3
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    arrays are always passed by reference in C and C++, never by value. Just leave out the '&' symbol.
    Code:
    oid LevelInit(level levels[], int lv){

  4. #4
    Registered User
    Join Date
    Feb 2006
    Posts
    21
    Okay, thanks, but... What if i want to access the members of the array passed?

    should i use

    Code:
    j[i].somemember();
    or
    Code:
    j[i]->somemember();
    Thanks again

  5. #5
    Registered User mrafcho001's Avatar
    Join Date
    Jan 2005
    Posts
    483
    Code:
    j[i]->something()
    Code:
    (j[i]).something()
    My Website
    010000110010101100101011
    Add Color To Your Code!

  6. #6
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    pass a pointer to the first element in the array

    here are two methods:
    Code:
    #include <iostream>
    
    void fooByContent(char*bar);
    void fooByCount(char*bar,const int num);
    
    int main()
    {
    	char line[]="Hello World";
    	fooByCount(line,11);
    	std::cout<<line<<std::endl;
    	fooByContent(line);
    	std::cout<<line<<std::endl;
    	return 0;
    }
    
    void fooByCount(char*bar,const int num)
    {
    	for(register short int i=0;i<num;i++)
    	{
    		bar[i]='A';
    	}
    }
    
    void fooByContent(char*bar)
    {
    	while(*bar)
    	{
    		*bar='B';
    		bar++;
    	}
    }
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  7. #7
    Registered User
    Join Date
    Feb 2006
    Posts
    21
    Thanks to everyone
    I had another problem with a windows exception, but it turns out it was a memory problem... Are arrays of classes THAT big?!

    Here is the class... an array of 100 threw an error, an array of 20 worked fine.
    What could I do to make "more" without using that much memory?
    Thanks for everything so far, you rule.


    Code:
    //"level" class definition
    class level{
          
    //Private members
          int efecto;            //HP change on the player (optional)
          string descripcion;    //Level description
          string opcion[6];      //Options to choose
          int resultado[6];      //Results of each option (next "level" to execute)
          
          
    //Constructors (default, explicit, destructor)
          public:
          level();
          ~level();
          level(int e, string d, string o1, string o2, string o3, string o4, string o5, int r1, int r2, int r3, int r4, int r5);
          
          
    //Methods
          public:
    		
    //Initializates a blank level just like the default constructor
    		void inicializarlevel(){
    			efecto = 0;
    			descripcion   = "Empty level";
    			opcion[0]     = "Null option";
    			opcion[1]     = "Empty option";
    			opcion[2]     = "Empty option";
    			opcion[3]     = "Empty option";
    			opcion[4]     = "Empty option";
    			opcion[5]     = "Empty option";
    			resultado[0]  = 0;
    			resultado[1]  = 99;
    			resultado[2]  = 99;
    			resultado[3]  = 99;
    			resultado[4]  = 99;
    			resultado[5]  = 99;
    		}
    
    		
    		
    			
    			
    //Takes a Player object as argument, to modify its Health if efecto is not 0
    //Shows the current level and its options
    		void iniciolevel(Player &p);
    
    //Takes two ints, the first (o) is the option the player chose
    //the second (p), sets the variable on "main" to the next level it has
    //to execute. This will be equal to one of the "resultado" members
          void eleccion(int o, int &p, bool &elecheck);
    };

  8. #8
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    well, first thing I see is your constructors... that last constructor would look alot better if you passed a struct in instead.

    second, you need better naming conventions. Capitalize the first letter of each word after the first for starters.

    Third, dont' forget each string is a class in itself, so every instance of this class comes along with 7 instances of the stl string class.

    fourth, how much memory do you have, and what does your array look like? If you're having trouble finding that much congruent space, consider a linked list, so you OS can split up the memory chunks, and you can dynamically allocate and deallocate parts of the game depending on memory constraints.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  9. #9
    Registered User
    Join Date
    Feb 2006
    Posts
    21
    Thanks for everything so far!

    first... I think that a struct wouldn't work, because the program uses each of the "options"

    second... Yeah, I'm still a begginer in this, I need to form the syntax and naming habits

    third... are strings that big?

    fourth... As I said before, i'm a bit "afraid" of pointers, as I always seem to get them wrong... I have heard a lot of times about "linked lists". What are they? I'd be really grateful if you could tell me... At least a simple explanation, thanks again, and sorry for the trouble


    EDIT: I have 768 DDR/333 RAM
    Last edited by Kylecito; 03-10-2006 at 10:12 PM.

  10. #10
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    I need to pass an array of "levels" by reference
    All arrays are passed by reference.

    Okay, thanks, but... What if i want to access the members of the array passed?

    should i use

    j[i].somemember();

    or

    j[i]->somemember();
    The '->' thinga-ma-jig is used when you have a pointer to a class object. It says: "Hey, Man-behind-the-Curtain, please dereferdefense my pointer and get the class member specified on the right for me--because it's too darn confusing for me to have to type: (*myPtr).member.

    Which line of code you use, depends on whether there are pointers to class objects in the array. This line:

    j[i].somemember();

    is equivalent to the syntax you use when you have an object of a class, e.g.:

    anObject.somemember();

    so if j[i] is an object of the class, then you use that syntax. If your array is full of pointers to objects, then you have to dereference the pointer to get an object with which to call a member function. So, if j[i] is a pointer to an object, you would use:

    j[i]->somemember();

    It's no secret that pointers are really confusing for me, especially pointers to arrays.
    So, don't use pointers to arrays:
    Code:
    void LevelInit(level levels[], int lv);
    
    LevelInit(myArrayName, 10);

  11. #11
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    as for that struct, try something like this:
    Code:
    #include <iostream>
    
    struct data
    {
    	int e;
    	std::string d;
    	std::string o1;
    	std::string o2;
    	std::string o3;
    	std::string o4;
    	std::string o5;
    	int r1;
    	int r2;
    	int r3;
    	int r4;
    	int r5;
    };
    
    void level(const data in);
    
    int main()
    {
    	data init;
    	init.e=0;
    	init.d="Data";
    	init.o1="Option One";
    	init.o2="Option Two";
    	init.o3="Option Three";
    	init.o4="Option Four";
    	init.o5="Option Five";
    	init.r1=1;
    	init.r2=2;
    	init.r3=3;
    	init.r4=4;
    	init.r5=5;
    
    	level(init);
    	return 0;
    }
    
    void level(const data in)
    {
    	std::cout<<"Data Dump:"
    		<<"\ne:  "<<in.e
    		<<"\nd:  "<<in.d
    		<<"\no1: "<<in.o1
    		<<"\no2: "<<in.o2
    		<<"\no3: "<<in.o3
    		<<"\no4: "<<in.o4
    		<<"\no5: "<<in.o5
    		<<"\nr1: "<<in.r1
    		<<"\nr2: "<<in.r2
    		<<"\nr3: "<<in.r3
    		<<"\nr4: "<<in.r4
    		<<"\nr5: "<<in.r5
    		<<std::endl;
    }
    this would be a good place to use arrays (if you get those memory problems resolved:
    Code:
    #include <iostream>
    
    struct data
    {
    	int e;
    	std::string d;
    	std::string options[5];
    	int r[5];
    };
    
    void level(const data in);
    
    int main()
    {
    	data init;
    	init.e=0;
    	init.d="Data";
    	init.options[0]="Option One";
    	init.options[1]="Option Two";
    	init.options[2]="Option Three";
    	init.options[3]="Option Four";
    	init.options[4]="Option Five";
    	
    	for(register short int i=0;i<5;i++)
    	{
    		init.r[i]=i+1;
    	}
    
    	level(init);
    	return 0;
    }
    
    void level(const data in)
    {
    	std::cout<<"Data Dump:"<<"\ne:  "<<in.e<<"\nd:  "<<in.d;
    	for(register short int i=0;i<5;i++)
    	{
    		std::cout<<"\no"<<i+1<<": "<<in.options[i];
    	}
    	for(register short int i=0;i<5;i++)
    	{
    		std::cout<<"\nr"<<i+1<<": "<<in.r[i];
    	}
    	std::cout<<std::endl;
    }
    Last edited by major_small; 03-11-2006 at 02:31 AM.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Passing a pointer to two-dimension array in a function
    By E_I_S in forum C++ Programming
    Replies: 11
    Last Post: 06-19-2008, 09:57 AM
  3. Warning while passing array by reference to function
    By Jdo300 in forum C Programming
    Replies: 11
    Last Post: 06-10-2008, 01:40 PM
  4. How to: Use OpenGL with Jgrasp
    By Pickels in forum Game Programming
    Replies: 3
    Last Post: 08-30-2005, 10:37 AM
  5. Passing a character array to a function
    By Qchem in forum C Programming
    Replies: 3
    Last Post: 03-07-2005, 07:18 AM