is there a short hand way of passing just a row in a 2d array into a function that accepts only 1d arrays. for example something like this even though I know that this doesn't work. I don't want to have to use loops to copy a row from the 2d array into a 1d array and then pass the 1d array into the function foo.

function foo(int array[4]) {
  do something
}

int main() {
    int test[2][4] = {{1,2,3,4},{5,6,7,8}};
    
    // pass only 1,2,3,4 into the function
    foo(test[0][]);
}

Edited 7 Years Ago by Talguy: n/a

That's an interesting idea TalGuy. I havn't written any code to test it, but one thing about arrays is the data is stored sequentially. Perhaps write the function to accept a pointer to the data type and the number of records to process, then pass the starting address for the row you wish it to process? Just a thought.

when passing the row from a 2D array to a function that takes a 1D parameter, use only the row index in your argument.

foo( test[0] );

That essentially passes a pointer to where that row begins.

Just out of idle curiosity I just tested it. Pretty much as I thought. You see, if you have a two dimensional array like test[2][4], then this...

test[1]

will represent the address of the second row. So yes, you can define a function taking a one dimensional array as a parameter (plus a count integer), and have it operate on any row which you pass to it from a two dimensional array. And I'm sure this is a general case true with arrays of higher dimension. I got it working in my test code anyway. Try this...

(piles of warnings you'll have to clean up, unfortunately)

#include <stdio.h>

int Sum1(int iArr[], int n)
{
 int iTot=0;

 for(int i=0;i<n;i++)
     iTot=iTot+iArr[i];

 return iTot;
}

int Sum(int* pInt, int n)
{
 int iTot=0;

 for(int i=0;i<n;i++)
     iTot=iTot+pInt[i];

 return iTot;
}


int main(void)
{
 int i,j;

 int test[2][4] = {{1,2,3,4},{5,6,7,8}};
 printf("Sum=%d\n\n",Sum(&test[1][0],4));
 for(i=0;i<2;i++)
     for(j=0;j<4;j++)
         printf("%u\t\t%d\n",&test[i][j],test[i][j]);
 printf("\n");
 printf("%u\n",test[1]);
 printf("Sum1=%u\n",Sum1(test[1],4));

 return 0;
}
This article has been dead for over six months. Start a new discussion instead.