Passing an array into a function

This is a discussion on Passing an array into a function within the C++ Programming forums, part of the General Programming Boards category; I've been trying to teach myself C off of the free tutorials here on the site. One of the things ...

  1. #1
    Registered User
    Join Date
    Aug 2006
    Posts
    1

    Passing an array into a function

    I've been trying to teach myself C off of the free tutorials here on the site. One of the things I keep running into in the Little practice programs I give myself is... well, passing an array into a function.

    I kinda figured pointers would be the way to go on this, but in reading the tutorial on pointers I didn't see a clear explanation and my subsequent experiments with them have mostly just lead to more confusion.

    Any pointers (pun semi-intended) on what I ought be doing for this specific problem, or insights as to bad habits I'm forming or better ways of displaying my code would be more than welcome.

    The code I'm pasting was intended to be (someday) a quizzer. It could load the questions and answers from a text file, save the results to a different text file, jump to different questions, load the questions in a random order etc etc. As you will be able to see it's... in development with some of the variables and functions declared but un-coded and some of them not even yet declared. The parts of the code that pertain to this question are high-lighted in red. The code it's self is commented to all hell too.

    I have /n mixed up with \n... I know it, I just haven't gone through and cleaned that out yet.
    Some of the code lines word-wraped on me when copy pasting, it's fairly obvious where this happened though and it isn't frequent.

    Code:
    #include <iostream>
    using namespace std;
    
    
    /*Variables-------------------------------------------------------------------*/
    
    int x = 0; //Keeps track of what problem number your currently working with.
    int y = 0; //Keeps track of the total questions.
    int l = 0; //Used to keep track of the second dimension in char answer[][]
    
    char answer[10][2]; //Keeps track of correct answers and answers submitted by user.
    
    
    For right now I'm just assuming there will be 10 questions with 10 corresponding answers etc etc.  
    It's going to be really messy to fix this later, but I figure that will be a learning experience for another day.  
    Probably when I try to tackle using classes.
    
    string question[10]; //Stores the question text to display to the user.
    
    string a[10]; //Stores the text of answer option a to display to the user.
    string b[10]; //Stores the text of answer option b to display to the user.
    string c[10]; //I think your getting it by now
    string d[10]; //Sure hope so at east.
    
    string input;
    
    string help = " Type HELP to view a list of available commands./n  Type OPEN to load a new quiz file./n 
    Type A, B, C, or D to answer the question./n";  
    
    int grade; //Stores the final score
    
    /*Function Prototypes---------------------------------------------------------*/
    
    void loader(int x, string question[x], string a[x], string b[x], string c[x], string d[x], char answer[x][2]);
    
    void submit(string input, int x, int y, char answer[x][1]);
    
    void score(int x, char answer[x][l], int grade);
    
    void display(int x, int y, string question[x], string a[x], string b[x], string c[x], string d[x], char answer[x][1]);
    
    /*Int Main--------------------------------------------------------------------*/
    int main() {
        cout<<help;
        cin>>input;
        cin.ignore();
        if (input == "OPEN") {
             loader(x, question[x], a[x], b[x], c[x], d[x], answer[x][2]);
             y==10
    }
        else if (input == "HELP") {
             cout<<help;
    }
        else if (input == "A" || input == "B" || input == "C" || input == "D" && y > 0) {
             submit(input, x, y, answer[][1]);
             display(x, y, question[x], a[x], b[x], c[x], d[x], answer[x][1]);
    }
        cin.get();
    }
    
    /*Function: Loader------------------------------------------------------------*/
    void loader (int x, string question[x], string a[x], string b[x], string c[x], string d[x], char answer[x][2]) {
    }
    
    /*Function: Submit------------------------------------------------------------*/
    
    void submit (string input, int x, int y, char answer[x][1]) {
    
         answer[x][1] = answer
         x = x++   
    }
    
    /*Function: Score-------------------------------------------------------------*/
    void score (int x, char answer[x][l]) {
         for (x = 0; x < y; x++) {
             if answer[x][1] == answer[x][2] {
                             grade = grade++
    }
    }                             
    }
    
    /*Function: Display-----------------------------------------------------------*/
    void display (int x, int y, string question[x], string a[x], string b[x], string c[x], string d[x], char answer[x][l]) {
         if x > y {
              score(int x, char answer[x][l], int grade);
         else {
              }
    }
    As you can see the question at hand is actually used in a lot more places than are turned red, but that specific example seemed like it would be the simplest and once I understand that part I should be able to get the rest.

    I thank you all much for any help you can offer.

  2. #2
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,262
    Just use a vector They're better, IMO.

  3. #3
    Registered User
    Join Date
    Feb 2006
    Posts
    312
    If you're just starting out with arrays, then try a program with 1-D arrays first. Things begin to get a whole lot more tricky when you add extra dimensions.
    Code:
    void submit(string input, int x, int y, char answer[x][1]);
    This is illegal, you cannot pass a parameter to a function, then use that to derive another parameter (in this case, one of the array dimensions)
    [Edit: Although you can do something similar with templates]

    The usual way to pass an array of C-Style strings is using a pointer to its first element, eg,
    Code:
    #include <iostream>
    
    void foo(char * arr[])
    {
        std::cout << arr[2];
    }
    
    int main()
    {
        char* bar[] = {"the", "quick", "brown", "fox"};
        foo(bar);
    }
    But as twomers said, using a vector, or any other STL container will save you a multitude of headaches.
    Last edited by Bench82; 08-29-2006 at 04:57 AM.

  4. #4
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,383
    You can use one of two methods:


    Code:
    void func( int[], int );  // method 1 (array parameter)
    void func2( int*, int );  // method 2 (pointer parameter)
    
    int main() {
        int arr[3] = { 0, 1, 2 };
        func(arr, 3);
        func2(arr, 3);
    }
    
    void func( int array[], int size ) { // method 1 (array parameter)
        for(int i = 0; i != size; ++i) {
            array[i] += 1;
        }
    }
    
    void func2( int* array, int size ) {  // method 2 (pointer parameter)
        for(int i = 0; i != size; ++i) {
            *array += 1;
            array++;
        }
    }
    Note that on both cases you should pass the array size or you will have little chance of knowing when to stop iterating through the array. For this and many other reasons, do as twomers suggested and read about vectors.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  5. #5
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,337
    Actually, it's very easy

    If you have
    Code:
    char array[10][20][30];
    Then one possible way of writing a function to accept this array is
    Code:
    /* Simply copy/paste the array declaration of the array you want to pass */
    void myfunc ( char array[10][20][30] ) {
      /* use exactly the same array notation as you would in the caller */
      /* just don't do sizeof(array) and expect the same answer as in the caller */
      array[0][0][0] = 'c';
    }
    Which you would call with (just like you would passing an int to a function expecting int)
    No additional & or *'s required here.
    Code:
    myfunc( array );
    If your compiler complains about the first dimension being useless (which it is), then you can edit it to
    Code:
    void myfunc ( char array[][20][30] )
    You can of course write it like this as well, but it's no different to the compiler
    Code:
    void myfunc ( char (*array)[20][30] )
    it's just extra effort on your part.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 02:07 AM
  2. Replies: 7
    Last Post: 11-21-2008, 03:27 PM
  3. function passing argument..array ?
    By jochen in forum C Programming
    Replies: 2
    Last Post: 09-30-2007, 11:53 AM
  4. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM

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