passing 2D array to a function

This is a discussion on passing 2D array to a function within the C Programming forums, part of the General Programming Boards category; How I can pass a 2-dimensional array to a function. The size of the array(m-by-n) is not the same each ...

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    29

    Unhappy passing 2D array to a function

    How I can pass a 2-dimensional array to a function.

    The size of the array(m-by-n) is not the same each time I run the program...
    C.B.Ashesh,
    Hyderabad, India

  2. #2
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,493
    I've asked this before...
    Unless the size of it is constant, you're better off putting it into a struct and passing that.

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    29
    The size of the array is not constant and changes dynamically...
    C.B.Ashesh,
    Hyderabad, India

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by ashesh
    The size of the array is not constant and changes dynamically...
    There aren't dynamicly sized arrays in C. (IE: You do not have valid C code.) Use malloc to malloc blocks of memory and just pass a pointer to said block.

    If in doubt, post your code example.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Sep 2001
    Posts
    29

    finally solved!!!

    main() {
    int *x;
    int r,c,i,j;
    printf("\nEnter r and c ");
    scanf("%d%d",&r,&c);
    x = (int *)malloc(sizeof(int)*r*c);
    for(i=0;i<r;i++)
    for(j=0;j<c;j++)
    scanf("%d",&x[i*r+j]);
    fun(x,r,c);
    printf("\n");
    }

    fun(int *x,int r,int c){
    int i,j;
    for(i=0;i<r;i++)
    for(j=0;j<c;j++)
    printf("%d\t",x[i*r+j]);
    }

    The above program works for a r-by-c matrix...
    C.B.Ashesh,
    Hyderabad, India

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 10-21-2007, 07:44 AM
  2. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 12:03 PM
  3. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  4. passing an array to a function (2d array)
    By revelation437 in forum C Programming
    Replies: 5
    Last Post: 03-11-2003, 02:32 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM

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