I am currently learning C in a Windows environment using MinGW compiler.
I cannot seem to pass variable length arrays to functions. I suspect it is the compiler I'm using but don't know for sure and wanted to know if anyone had any thoughts on what the problem could be. I don't think it's an issue with syntax because I have seen the same syntax all over the place while researching the issue.
At the end of this post is sample code from one of the books that I'm reading (C Primer Plus by Stephen Prata) that won't compile for me. I've also tried writing my own code with similar results. The problem seems to be with this function declaration line:
int sum2d(int rows, int cols, int ar[rows][cols]);
The error I'm getting is: "use of parameter outside function body before ']' token int sum2d(int rows, int cols, int ar[rows][cols]);"
The issue seems to be that I can't use the int rows and int cols parameters, which are also getting passed to the function, as indexes in the array that is also getting passed. My work around for now has been to keep variable length arrays within the main function but that limits my ability to modularize my code.
I found some posts, like these, that seem to be discussing the same issue in C++: int[n][m], where n and m are known at runtime and Passing 2D array with variable Size. But every post I've found on the topic has been about C++ rather than C and they all say that it will work with C but not with C++. But I'm finding it doesn't work for C either. Many of these links discuss using vector
. I'm not far enough along in my C learning to know if vector
is even available in C. For now, I'm just wondering if anyone knows why passing variable length arrays to functions is not working for me.
Example from the book:
//vararr2d.c -- functions using VLAs
#include <stdio.h>
#define ROWS 3
#define COLS 4
int sum2d(int rows, int cols, int ar[rows][cols]);
int main(void)
{
int i, j;
int rs = 3;
int cs = 10;
int junk[ROWS][COLS] = {
{2,4,6,8},
{3,5,7,9},
{12,10,8,6}
};
int morejunk[ROWS-1][COLS+2] = {
{20,30,40,50,60,70},
{5,6,7,8,9,10}
};
int varr[rs][cs]; // VLA
for (i = 0; i < rs; i++)
for (j = 0; j < cs; j++)
varr[i][j] = i * j + j;
printf("3x5 array\n");
printf("Sum of all elements = %d\n",
sum2d(ROWS, COLS, junk));
printf("2x6 array\n");
printf("Sum of all elements = %d\n",
sum2d(ROWS-1, COLS+2, morejunk));
printf("3x10 VLA\n");
printf("Sum of all elements = %d\n",
sum2d(rs, cs, varr));
return 0;
}
// function with a VLA parameter
int sum2d(int rows, int cols, int ar[rows][cols])
{
int r;
int c;
int tot = 0;
for (r = 0; r < rows; r++)
for (c = 0; c < cols; c++)
tot += ar[r][c];
return tot;
}