简体   繁体   中英

How to pass a 2-D array's specific row as a 1-D array to a function in C?

I have a function which takes a 1-D array as its parameter. The values that I want to pass to this function are present in a specific row of a 2-D array . How do I pass that row as a 1-D array to the function?

You can pass the nth row of a 2d array ( array[x][y] ) to a function ( func ) using one of the following ways. Make sure to pass size of the the array ( nth row ) to func .

  • func(array[n], y);
  • func(&array[n][0], y);
  • func(*(array+n), y);

Each of the above expression evaluates to the same value (viz. the address of first element in nth row )

#include <stdio.h>

void foo(int *x, size_t n) {
    printf("%d\n", x[0]); /* marks[10][0] */
    if (n > 10) printf("%d\n", x[10]); /* marks[10][10] */
}

int main(void) {
    int marks[42][42] = {0};
    foo(marks[10], sizeof marks[10] / sizeof marks[10][0]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM