2D array, function call question in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • primpa
    New Member
    • Aug 2007
    • 9

    2D array, function call question in C

    Hi
    I have a question when I call a function and creating a pointer to a 2D array in the main function. "Main" call a function to input data in a array witch is declared in the main function.
    Witch works perfectly well, however I would like only to send the first row of my 2D array, or only the second row, only the third row etc. A.t.m. I send the entire array, and don´t know how to just send one row at a time to the function, of the array. In the input function i input data from the keyboard using fgets.


    Would really appreciate an answer

    Thanks
  • RedSon
    Recognized Expert Expert
    • Jan 2007
    • 4980

    #2
    If you want to send one row it is best to copy that row into a new array and pass that.

    Comment

    • ahoyer
      New Member
      • Aug 2007
      • 14

      #3
      Originally posted by primpa
      Hi
      I have a question when I call a function and creating a pointer to a 2D array in the main function. "Main" call a function to input data in a array witch is declared in the main function.
      Witch works perfectly well, however I would like only to send the first row of my 2D array, or only the second row, only the third row etc. A.t.m. I send the entire array, and don´t know how to just send one row at a time to the function, of the array. In the input function i input data from the keyboard using fgets.


      Would really appreciate an answer

      Thanks
      because the rows are laid out in memory in row major, its quite simple to send just the individual rows. you dont need to copy anything.

      try this code:
      Code:
      #include<stdio.h>
      
      /*funct takes a 1d array as an argument and prints out
      its values, it needs to know the number of columns of your
      original array though*/
      void funct(int* array, int size){
      	int i;
      	printf("inside funct\n");
      	for(i=0; i<size; i++){
      		printf("%d ", array[i]);
      	}
      	printf("\n");
      	return;
      }
      
      int main(){
      	int marray[3][5];
      	int i, j, k;
      	/*filling "marray" with values*/
      	for(i=0, k=0; i<3; i++){
      		for(j=0; j<5; j++){
      			marray[i][j] = k;
      			k++;
      		}
      	}
      	/*printing out "marray" just to make sure its full*/
      	for(i=0; i<3; i++){
      		for(j=0; j<5; j++){
      			printf("%d ", marray[i][j]);
      		}
      		printf("\n");
      	}
      	printf("pass each row\n");
      	/*passing the individual rows to the "funct" function*/
      	for(i=0; i<3; i++){
      		funct(marray[i], 5);
      	}
      	return 0;
      }
      marray is the 2d array, the first for loop just fills marray with numbers, the second one prints it out just to show you, and the third loop passes the individual rows into a function called funct that prints them out.

      hope that helps!

      :)

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Originally posted by primpa
        however I would like only to send the first row of my 2D array, or only the second row, only the third row etc. A.t.m. I send the entire array, and don´t know how to just send one row at a time to the function, of the array.
        In C and C++ you cannot pass an array to a function. Function arguiments can only be a type or a pointer to a type. An array is not a type. Therefore, an array is a pointer.

        The rule is that the name of the array is the address of element 0. When you pass the array to a funciton, you pass only the address of element 0.

        Consider this:
        [code=c]
        int arr[3][4];
        [/code]

        There arr is an array of 3 elements. Each element is an array of 4 elements. Usng the rule, arr is the address of element 0, so arr is the address of an array of 4 int. So, declare a pointer to an array of 4 int:

        [code=c]
        int (*ptr)[4];
        [/code]

        You can assign the address of any row to this pointer:

        [code=c]
        ptr = arr;
        ptr = &arr[1];
        //etc..
        [/code]

        For a function, the argument must be a pointer to an array of 4 int:

        [code=c]
        void MyFunction(int (*arg)[4], int numelements)
        {

        }
        [/code]

        All you need to is pass the address of an array of 4 int and the number of arrays of 4 int there are.

        Comment

        • primpa
          New Member
          • Aug 2007
          • 9

          #5
          Thanks allot for the reply´s, they did clear some questions out.

          I did not express my self clear enough thou, when I call a function and send my 2D array to it as a pointer like this:

          Code:
           
          int input_data(char *);   //function declaration
          
          
          int main(char myarray[2][3]) 
          {
          input_data(myarray[2]);  // function call in main
          }
          
          int input_data(char *arr)  // function start here 
          {
          ... // fgets to read in some data
          }
          thou, this is not the problem, i want the function "input_data " to only recive the second row in the array "myarray" so the pointer "*arr" points to row 2 and column 0. maybe i am doing something wrong, but if i call the function twice, once with the argument (myarray[0]) and once withe the argument (myarray[2]) the later will overwrite the first row of the array.
          maybe this is not possible, then correct me. otherwise i would gladly like to know how to do it =)

          thanks for reply´s

          Comment

          • 2wycked
            New Member
            • Aug 2007
            • 14

            #6
            Originally posted by primpa
            Code:
             
            int input_data(char *);   //function declaration
            
            
            int main(char myarray[2][3]) 
            {
            input_data(myarray[2]);  // function call in main
            }
            
            int input_data(char *arr)  // function start here 
            {
            ... // fgets to read in some data
            }
            Well, the first thing is that myarray[2] is not defined. myarray only has rows 0 and 1, so who knows what you're actually sending the function. Other than that, I don't see a problem with the code.

            Comment

            • gsi
              New Member
              • Jul 2007
              • 51

              #7
              hi,
              Your main() should take in 2 arguments , the first one being the number of actual arguments passed and the second one being the actual arguments itself. Secondly main takes in an array of char pointers as the second argument. Although arrays are passed in as implicit pointers, the second parameter in the main prototype must be explicitly declared as an array of char pointers not as what as u have done. This may be because,

              Consider 2 declaration's
              1. char *a = "hai";
              2. char b[] = "hai"

              Here pointer a may be made to point anywhere after this declaration but b since being an aggregate object allocated statically cannot be made to point anywhere else. The same is analagous to your case of myarray[2][5], since the space delimited user inputs are allocated as cstyle strings after the user types in and their corresponding pointers are assigned individually to your second array argument.
              I am not sure of this , pls correct me if I am wrong.

              It may be like,

              [code=c]
              int main(int argc, char **myarray){
              input_data(myar ray[1]); // ---> myarray[0] will be ur executable name !!!
              }
              [/code]

              Either way is fine , char **myarray or char *myarray[].

              Thanks,
              gsi.

              Comment

              • weaknessforcats
                Recognized Expert Expert
                • Mar 2007
                • 9214

                #8
                Originally posted by 2wycked
                int input_data(char *); //function declaration
                That function is expecting a pointer to a single char.

                Did you read my Post #4??

                You can't pass an array to a function. All you can pass is the address of element 0.

                Comment

                • 2wycked
                  New Member
                  • Aug 2007
                  • 14

                  #9
                  Originally posted by weaknessforcats
                  That function is expecting a pointer to a single char.

                  Did you read my Post #4??

                  You can't pass an array to a function. All you can pass is the address of element 0.
                  For 2D arrays, such as myarray[2][3], a value of myarray[i] would be a pointer, not an int (or char, or whatever type). Just as if you declared myarray as char** myarray, a value of *myarray will be a pointer, but a value of *(*myarray) will be a char.

                  Comment

                  • primeSo
                    New Member
                    • Aug 2007
                    • 35

                    #10
                    Originally posted by primpa
                    Thanks allot for the reply´s, they did clear some questions out.

                    I did not express my self clear enough thou, when I call a function and send my 2D array to it as a pointer like this:

                    Code:
                     
                    int input_data(char *);   //function declaration
                    
                    
                    int main(char myarray[2][3]) 
                    {
                    input_data(myarray[2]);  // function call in main
                    }
                    
                    int input_data(char *arr)  // function start here 
                    {
                    ... // fgets to read in some data
                    }
                    thou, this is not the problem, i want the function "input_data " to only recive the second row in the array "myarray" so the pointer "*arr" points to row 2 and column 0. maybe i am doing something wrong, but if i call the function twice, once with the argument (myarray[0]) and once withe the argument (myarray[2]) the later will overwrite the first row of the array.
                    maybe this is not possible, then correct me. otherwise i would gladly like to know how to do it =)

                    thanks for reply´s
                    The paramaters in main() is wrong. Someone has mentioned above, you can check it out. BTW, i think your understanding of array is not right. You want your function input_data() to only receive second row of the array "myarray", then optionally, you can choose to pass the second row of the array in main by
                    Code:
                      input_data(myarray[1]);
                    , this mean, " a copy of the address of the first element in the second row will be make and pass to function input_data()" . You can use a for loop to pass one row each time you call the function, this can loop through every row and process each row accordingly. Remember, in the context of 2D array, when you only invoke the first subscript , it imply a pointer to a certain row only. In your case, you only have 2 row in the array, how do you pass myarray[2]? This mean the 3rd row in the array, compile error though.

                    You call the function twice? That mean the first time you call the function, no matter what value *arr has would "die" when u exit the function. I don't really understand what do you mean by "overwrite" , this depends on your program's task.

                    Comment

                    • gsi
                      New Member
                      • Jul 2007
                      • 51

                      #11
                      Hi ,
                      Sorry for the confusion, Since u only need in column-zero it may be like

                      [code= cpp]
                      int main(int argc, char **myarray){ // char *myarray[3] is also fine.
                      input_data(myar ray[i][0]);
                      }
                      [/code]
                      loop in the variable ' i ' for the no. of rows desired, in your case it is 1 to 2 (Assuming that the user input is two space delimited c style strings and u dont need the executable name). Exceeding this results in undefined behaviour (c/c++ Compiler's doesn't check this and even the runtime environment does't do this for execution speedup) .

                      Thanks,
                      gsi.

                      Comment

                      Working...