C Programming: Pointer to a row of a 2D array?
I wrote a function that returns a pointer to a 1D array. The function 开发者_开发知识库prototype is:
double* NameFunction (int,double*,double*)
The function seems to work fine with 1D array.
Here's the question: I'd like to use the function to fill one row of a 2D array.
How do I write in the calling function a pointer to the row of the 2D array to fill?
Can I use the same pointer structure to indicate a row of a 2D array as argument?
Yes just pass the name of the 2D array with the first index filled in:
NameFunction (12121212,&array[0],some pointer here) // for example if you want to pass the first row
A variable pointing to an array in C always contains just an address location i.e., the pointer to the starting of the array. So, whatever the array type, it just needs a pointer which is a *.So this function should work as it is now.
But you may need to change some programming logic.
You can take double foo[20]
as 1×20 array, or you can take it as two-dimensional 4×5 array. Then you have the coordinates like this:
foo foo+1 foo+2 foo+3 foo+4
foo+5 foo+6 foo+7 foo+8 foo+9
foo+10 foo+11 foo+12 foo+13 foo+14
foo+15 foo+16 foo+17 foo+18 foo+19
So if you have a function that returns double *
, you can pass it (or make it return) foo + 5*n
to point at row n
.
#define ROW_LEN 5
#define ROWS 4
void fillRow(double * row)
{
int i;
for (i = 0; i < ROW_LEN; i++)
{
row[i] = 12;
(row + i) = 12; // this is the same thing written differently
}
}
double arr[ROW_LEN * ROWS];
fillRow(arr + 2 * ROW_LEN); // fill third row
Note that C does not do any range checking at all, so if you are not careful and accidentally to something like arr[627] = 553
somewhere in your code, it's going to blindly overwrite everything that is at the computed address in the memory.
精彩评论