Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Passing a 2d array to a function in C

  1. Nov 8, 2008 #1
    I am currently writing a simulation of the game of life in C. I can create a dynamically sizes 2d array in C. However I then want to pass this array to a function.

    I have tried to do this however I cannot pass the array if at least one of the dimension sizes and not defined at compile time.

    Does any one know how to do this?
     
  2. jcsd
  3. Nov 8, 2008 #2

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    There is no way in C to pass an array to an function. The normal way would be to pass a pointer to the array and then the size as separate arguements.
     
  4. Nov 8, 2008 #3
    I was aware that I would have to pass a pointer but when I try to do this it message up also.

    Picture this. I have a 2d array for arguments sakes lets say 50 x 50. I can pass it as a pointer and I can pass it 2 other arugments which are the dimensions. However when I try to reference the array via the pointer it messes up. And seems to put the elements in a different order.

    I know I am most likely pushing it a little here for a noob, but is there any chance that someone would be kind enough to provide me some sample code to do this?
     
  5. Nov 8, 2008 #4
    Try:

    Code (Text):
    #include <stdio.h>
    #include <stdlib.h>
    #include <malloc.h>
    // Ref : http://www.eskimo.com/~scs/cclass/int/sx9b.html
    void printArray(int **array, int m, int n)
    {
     for(int i=0;i<m;i++)for(int j=0;j<n;j++)printf("%d\n",array[i][j]);
    }
    int main()
    {
          int i,j,k=0, m=5, n=20;
          int **a=(int **)malloc(m*sizeof(int *));
          for(i=0;i<m;i++)a[i]=(int *)malloc(n*sizeof(int));
          for(i=0;i<m;i++)for(j=0;j<n;j++){k++; a[i][j]=k;}
          //for(i=0;i<m;i++)for(j=0;j<n;j++)printf("%d\n",a[i][j]);
          printArray(a,m,n);
          system("PAUSE");
          return 0;
    }
     
  6. Nov 8, 2008 #5

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    If this is the actual purpose of your efforts (rather than trying to learn a lesson in low-level C memory management), then you really ought to consider using a different language which makes these sorts of things much easier. (e.g. switch to C++, and make use of the standard containers, probably std::deque)
     
  7. Nov 8, 2008 #6
    Many thanks that last one does appear to have done the job. I will have a go at implementing it into my app and I will report back.

    A thousand thanks
     
  8. Nov 8, 2008 #7
    I have thought of this however I do not get along well with OOP. I have to study it at uni and I can see the advantages however I just don't think like it and I find it hard to write. I get along a lot better with function/procedural programming.
     
  9. Nov 8, 2008 #8

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Who said anything about OOP? I was only talking about data types! And the std::deque<std::deque<int> > type is far easier (and safer!) to use than the int** type for two-dimensional dynamic arrays.
     
  10. Nov 8, 2008 #9
    I apologise, I am unfamiliar with C++. I have taught myself C. And all I get taught at uni is Java which is a beast of a language. And I don't mean 'beast' in a good way.
     
  11. Nov 8, 2008 #10
    For some reason I have had an email saying you have reply and i can read it on my mail but it isn't appear in the forum. Anyway, I have read your code and I can see roughly what it is doing however I am not competant in C++ to be able to fulfil the rest of my goal in C++.

    I am currently implementing first suggestion with some success.
     
  12. Nov 8, 2008 #11
    Another quick Q. How would I then free the allocated memory once I have done with it?
     
  13. Nov 8, 2008 #12
  14. Nov 8, 2008 #13
    Just checking, with the code that you kindly provided for me in the first place. I should be able to create a rectangular array shouldn't I? (i.e one where the rows are greater than the columns or visa versa)
     
  15. Nov 8, 2008 #14
    Never mind sorted the different dimension problem
     
  16. Nov 8, 2008 #15
    Yes, you can do better than that.
    Following the same procedure, you can make mxn, nxm, mxm arrays, i.e. any shape you want.
    Even better than that, you can make jagged arrays where the rows are of different sizes.
    Even further, following the same principle, you can make 3+ dimension arrays. Obviously in these cases, you need to nest deeper than the example.
    Good luck with your work!
     
  17. Nov 8, 2008 #16
    Might have a go at 3d game of life after I have finished the dynamic 2d version. 3d should be a good task. However trying to work out the rule set and a visualisation method could be somewhat interesting.
     
  18. Nov 8, 2008 #17
    Great!
    Let us know from time to time how you're doing.
     
  19. Nov 9, 2008 #18
    Will do, I will most likely end up asking more questions about it anyway.
     
  20. Jan 14, 2011 #19
    Code (Text):

    #include<stdio.h>
    #include<stdlib.h>


    void function(int **x);


    main()
    {
      int nrows=2,ncolumns=2,i,j;


      //memory allocation for x
      int **x=malloc(nrows*sizeof(int*));
      if(x==NULL)
        {
          printf("out of memory\n");
          return 0;
        }
      for(i=0;i<nrows;i++)
        {
          x[i]=malloc(ncolumns*sizeof(int));
          if(x[i]=NULL)
        {
          printf("out of memory\n");
          return 0;
        }
        }


      printf("code passed me");//checking


      //define x
      for(i=0;i<2;i++)   
        for(j=0;j<2;j++)       
          x[i][j]=i+j+2;
     




      //call function
      function(x);

    }







    //function_definition
    function(int &x)

    {
      int nrows=2,ncolumns=2,i,j,y[2][2];

             
      for(i=0;i<2;i++)
        for(j=0;j<2;j++)
          y[i][j]=x[i][j]+1;



      //display y
      for(i=0;i<2;i++)
        for(j=0;j<2;j++)
          printf("%d",y[i][j]);      
    }
     
    segmentation fault comes.. help please
     
  21. Jan 15, 2011 #20

    rcgldr

    User Avatar
    Homework Helper

    one of the issues with C's syntax (some compilers will optionally generate a warning for this), make that
    Code (Text):

          if(x[i]==NULL)
     
    You can also do this with a single allocation:

    Code (Text):


    // single allocation for x (data starts after array of pointers (x+nrows))

    int **x=malloc(nrows*sizeof(int*) + (nrows*ncolumns*sizeof(int));

        if(x==NULL)
        {
          printf("out of memory\n");
          return 0;
        }

        for(i=0;i<nrows;i++)
        {
          x[i]=(int *)((int)(x+nrows) + i*ncolumns*sizeof(int));
        }

    // ... rest of code ...

        free(x);
     
     
    Last edited: Jan 15, 2011
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Passing a 2d array to a function in C
Loading...