Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

C++ help

Options
  • 22-02-2006 5:31pm
    #1
    Registered Users Posts: 8,438 ✭✭✭


    I am looking for advice.
    I have a two dimensional array in a function of a program that works nicely.
    i now need to alter the program and access the array from another funtion, BUT i don't need the parameters passed and returned etc. i'd prefer not to make it global unless necessary. i've heard this may be done with pointers but it's a little over my head. any help would be really appreciated.


Comments

  • Registered Users Posts: 1,481 ✭✭✭satchmo


    Google for "arrays as pointers", should be plenty of info for you to get started. You should think of a 2D array as an array of 1D arrays (ie an array of pointers).


  • Registered Users Posts: 8,438 ✭✭✭RedXIV


    will that work? can i declare a pointer in one function to point to an array in another?


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    Nope.

    If i create a variable in function X, then i can't access it from function Y.

    (unless function X returns that array on completion, and i then feed that array into function Y as a paramater).


  • Registered Users Posts: 8,438 ✭✭✭RedXIV


    thats what i thought.......damn




    back to drawing board. thanks for advice. will undoubtably be back soon


  • Registered Users Posts: 1,481 ✭✭✭satchmo


    Like Mutant_Fruit said, that won't work - a rough guide is this: nothing outside curly braces {...} will be able to see a variable created inside those braces. This is a variable's scope.

    Read this tutorial on pointers, you should have a better grasp of them afterwards. I think you might do well to go through some of the other tutorials on that site too.


  • Advertisement
  • Registered Users Posts: 8,438 ✭✭✭RedXIV


    now thats cleared alot up, thanks guys, much appreciated


  • Registered Users Posts: 18 suavek


    Ok, this way of doing things is very, very evil and I alredy feel guilty for posting this ;)
    #include <iostream>
    
    void test1()
    {
    	static int x[10][10];
    	std::cout << x[0][0] << std::endl;
    }
    
    void test2()
    {
    	static int x[1][1];
    
    	void* evil_ptr = x - 100;
    	*((int*)evil_ptr) = 5;
    
    	// should you want to change different element of that array don't use this pattern:
    	// *(10 * row + column + (int*)evil_ptr) = something
    }
    
    int main()
    {
    	test1();
    	test2();
    	test1();
    }
    


  • Registered Users Posts: 1,481 ✭✭✭satchmo


    Jesus, why the hell would you want to do it like that?


  • Registered Users Posts: 4,003 ✭✭✭rsynnott


    suavek wrote:
    Ok, this way of doing things is very, very evil and I alredy feel guilty for posting this ;)
    #include <iostream>
    
    void test1()
    {
    	static int x[10][10];
    	std::cout << x[0][0] << std::endl;
    }
    
    void test2()
    {
    	static int x[1][1];
    
    	void* evil_ptr = x - 100;
    	*((int*)evil_ptr) = 5;
    
    	// should you want to change different element of that array don't use this pattern:
    	// *(10 * row + column + (int*)evil_ptr) = something
    }
    
    int main()
    {
    	test1();
    	test2();
    	test1();
    }
    

    DO NOT USE THIS.

    It depends on placement of things in memory that is not guaranteed. At all.


  • Registered Users Posts: 2,082 ✭✭✭Tobias Greeshman


    Something like this is a lot more safer, that other code is lethal it could do anything.
    #include<stdio.h>
    
    void func1 ( void ) ;
    void func2 ( int parray [ ] [ 10 ], const int first_dimension  ) ;
    
    int main ( int argc, char** argv )
    {
      func1 ( ) ;
    
      return 0;
    }
    
    void func1 ( void )
    {
      int twod_array [ 10 ] [ 10 ] ;
      
      /* Do whatever processing with array */
    
      func2 ( twod_array, 10 ) ;
    }
    
    void func2 ( int parray [ ] [ 10 ], const int first_dimension  ) 
    {
       /* Make changes to parray, or make a copy of it if you don't 
        * want to change parray... 
        */
    
    }
    


  • Advertisement
  • Registered Users Posts: 18 suavek


    Of course I would never use this! I thought that the "it's evil... I feel guilty" line at least hinted this code should not be taken seriously. I'm not a native English speaker though so probably it didn't sound the way I wanted it to. Still learning, you see.

    I promise to refrain from posting frivolous code in future :)


  • Registered Users Posts: 8,438 ✭✭✭RedXIV


    hey! :D my code is now pretty similar in structure to the one silas posted up, and that fact that it's here has boosted confidence incredibly. Also really happy i didn't try to use suavek's, didn't understand it anyway :confused:

    thanks for all the help lads!


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    I don't do C++, so my syntax might be wrong... but this would work too...

    #include <iostream>
    
    void test1(int x[][])
    {
    	std::cout << x[0][0] << std::endl;
    }
    
    void test2(int x[][])
    {
          for(int i=0; i<10; i++)
              {
                   x[i][0] = 5;
              }
    }
    
    int main()
    {
    	int x[10][10];
    
    	test1(x); // send test 1 the 'x' array
    	test2(x); // send test 2 the same x array
    	test1(x); // resend the same 'x' array to test 1 again after test 2 changed it
    }
    

    I assume that in C++ passing an array like that means that the original array is sent to the functions and a local copy isn't created and destroyed. Therefore any changes made in test2 won't be lost when that function ends.


  • Registered Users Posts: 4,003 ✭✭✭rsynnott


    suavek wrote:
    Of course I would never use this! I thought that the "it's evil... I feel guilty" line at least hinted this code should not be taken seriously. I'm not a native English speaker though so probably it didn't sound the way I wanted it to. Still learning, you see.

    I promise to refrain from posting frivolous code in future :)

    No need to do that :) It just wasn't terribly obvious that it was a joke (people used to do this sort of thing as optimisation, and in fact if you can say with certainty that your program will only ever be run on X chip compiled with Y compiler using Z clibs, you could still get away with it today. (Video card drivers have a particular reputation for doing naughty things). )


  • Registered Users Posts: 8,438 ✭✭✭RedXIV


    ok, i've figured out how to get around my earlier problem (thanks guys) next question, i've got my 2D array, it's used throughout my program, my new function can access and change this array, but when i return to my main function and try and access the array, the compiler tells me i'm trying to overwrite forbidden memory. anyone know why, and more importantly, how can i stop it?


  • Registered Users Posts: 1,481 ✭✭✭satchmo


    rsynnott wrote:
    (Video card drivers have a particular reputation for doing naughty things)
    Really? I'd be interested in hearing any more you know about this...


  • Registered Users Posts: 18 suavek


    RedXIV, your description of what you're doing is too vague, you need to post some more details. A code sample wouldn't hurt.

    rsynnott, I feel a deep compassion for people who had to maintain code optimised that way :D


  • Registered Users Posts: 8,438 ✭✭✭RedXIV


    okie dokie, I'm making a quiz.
    you get 4 random questions of a bank of 20 (thats my 2D array)
    you can take up to three quizes and then the program ends.
    the bit thats causing me hassle is i want an admin option where you can change the questions, ie the 2D array, and use it in the main program.
    i have this altering of the array in a function and the quiz itself uses three other functions as well as the main one. it runs perfectly until i change a question in the admin panel, go back to the main menu, and try to start a quiz, the program tries to access the arrays and the compiler breaks down.
    //******************************************************************************
    //Function Name:                ChangeQuestions()
    //Function Purpose:
    //Parameters passed to:
    //Parameters returned:
    //******************************************************************************
    
    
    void changeQuestions(char pQuestions[][100], char pActualAnswers[][100], char pAnswers[][8])
    {//start of changeQestions
    
    int choice;
    char option='y';
    clrscr();
    
    
      while (option == 'y' || option == 'Y')
      {//Start of while
    
    
    for (int loop=0;loop<20;loop++)
    cout << pQuestions[loop]<<endl;
    cout << "\n\nPlease choose a question to alter: ";
    cin >> choice;
    clrscr();
    cout << pQuestions[choice];
    cout <<"\n\nPlease enter a new question of 100 characters or less: "<< endl;
    gets(pQuestions[choice]);
    
    cout << "\n\nPlease enter in your answer. Either \"True\" or \"False\ " <<endl;
    gets(pAnswers[choice]);
    
    cout << "\n\nNow please enter the ACTUAL Answer " <<endl;
    gets(pActualAnswers[choice]);
    
     cout << "\n\n\Do you want to alter another question? (Y)es or (N)o?";
     cin >> option;
    
     }//end of while
    
    
    }//end of change
    


    thats the admin piece of code


    EDIT: Just discovered that i can't even run it now even if i go straight to the quizzes. how do i make sure the arrays aren't initilised on memory thats forbidden?


  • Registered Users Posts: 18 suavek


    Well, I don't see much point in using C-style "strings as arrays of chars" approach in C++. There's a string class in C++ that makes lots of things much easier. Using bare chars is asking for trouble IMHO.
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
       string questions[10] = {"Question one", "Question 2", "..." };
       
       // you can't do this with a 2D array of chars, but you can with an array of strings:
       questions[5] = "Question number 6";
       
       // when you want to read whole line into a string
       getline(cin, questions[3]);
    }
    
    Check out this link
    And this one too

    As for your code, at the moment I can't see anything that could cause the behaviour you describe. This code is bad because it would break horribly in case someone entered more than 100 characters... Try rewriting your program using C++ strings, your problem should go away :)


  • Registered Users Posts: 8,438 ✭✭✭RedXIV


    ................Really not impressed with college lecturer for never mentioning the string data type. i know i'm only starting but that would have made things alot easier. thanks a million for the information, hopefully this will be the end of my problems, but keep checking anyway :D


  • Advertisement
  • Registered Users Posts: 18 suavek


    One more advice - download this book - it's free and it's great. I loved it. It's not written in "teach yourself something in 24 hours" style and some people accuse Eckel of being long-winded... you have to judge by yourself. just give it a try.


  • Registered Users Posts: 1,481 ✭✭✭satchmo


    He probably didn't tell you about the string class because he wants you to learn about character arrays first. There are a couple of things to be learned from doing strings the hard way, and it helps you get your head around pointers and arrays (which do seem to be the things you're having problems with) by using them in a practical context.


  • Registered Users Posts: 8,438 ✭✭✭RedXIV


    don't you feel sickened when it's something stupid. forgot to initilise something. program was looking for the 1,243,623th cell of an array, which is a tad over what i need, thanks for all help anyway guys


  • Registered Users Posts: 4,003 ✭✭✭rsynnott


    satchmo wrote:
    Really? I'd be interested in hearing any more you know about this...

    There was an interesting post on one of the MSDN blogs on the subject recently. Can't find it offhand.


Advertisement