I have to write a program which illustrates the usage of pointers with arrays and functions.
#include <stdio.h>
#include <conio.h>
#define ROWS 3
#define COLS 4
void print(int rows, int cols, int *matrix);
void main(void)
{
int a[ROWS*COLS],i;
for(i=0;i<ROWS*COLS;i++)
{
a[i]=i+1;
}
print(ROWS,COLS,a);
getch();
}
void print(int rows, int cols, int *matrix)
{
int i,j,*p=matrix;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%3d",*(p+(i*cols)+j));
}
printf("\n");
}
}
The above program prints a matrix with the rows and columns predefined. I want to modify the program such that the rows and columns are entered by the user.
#include <stdio.h>
#include <conio.h>
void print(int rows, int cols, int *matrix);
void main(void)
{
int ROWS,COLS,a[ROWS*COLS],i;
printf("Enter the number of rows: ");
scanf("%d",ROWS);
printf("\nEnter the number of columns: ");
scanf("%d",COLS);
for(i=0;i<ROWS*COLS;i++)
{
a[i]=i+1;
}
print(ROWS,COLS,a);
getch();
}
void print(int rows, int cols, int *matrix)
{
int i,j,*p=matrix;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%3d",*(p+(i*cols)+j));
}
printf("\n");
}
}
This programs is giving an error that the variables ROWS and COLS are being used before they are being declared. How to solve this problem.
One option is to allocate
aon the heap:Notice also that I’ve:
scanf()calls;main()toint. See What are the valid signatures for C's main() function?As you why your code didn’t work:
Traditionally, C required constant expressions for array bounds. When
ROWSandCOLSwere constants, everything was good with your code. Once you’ve turned them into variables,abecame a variable-length array. The problem was that the size of the array is computed at the point where the array is declared, and at that point the values ofROWSandCOLSwere not yet known.In C99, it is possible to fix your code by pushing the declaration of
adown: