Skip to content

Instantly share code, notes, and snippets.

@joyeecheung
Created November 27, 2014 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyeecheung/cd4c06049e4a5e24aed9 to your computer and use it in GitHub Desktop.
Save joyeecheung/cd4c06049e4a5e24aed9 to your computer and use it in GitHub Desktop.
Variable length array as function parameter, casted before passing, using GNU C forward parameter declaration
// compile me with `gcc -std=c99` or `gcc -std=gnu99`
#include <stdio.h>
int sum(int n_col; int arr[][n_col], int n_row, int n_col) {
int i, j, total = 0;
for (i = 0; i < n_row; ++i) {
for (j = 0; j < n_col; ++j) {
total += arr[i][j];
}
}
return total;
}
int main(int argc, char *argv[]) {
int n_col = 5, n_row = 5;
int arr[25];
int i, j;
for (i = 0; i < n_row; ++i) {
for (j = 0; j < n_col; ++j) {
arr[i * n_col + j] = 1;
}
}
printf("%d\n", sum((int (*)[n_col])arr, n_row, n_col));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment