如何在使用之前初始化数组元素?

Rae*_*hid 1 c arrays initialization

我必须编写一个程序来说明指针与数组和函数的用法.

#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");
   }
}
Run Code Online (Sandbox Code Playgroud)

上面的程序打印出一个预定义行和列的矩阵.我想修改程序,以便用户输入行和列.

#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");
   }
}
Run Code Online (Sandbox Code Playgroud)

这个程序给出了一个错误,即变量ROWS和COLS在被声明之前被使用.如何解决这个问题呢.

NPE*_*NPE 5

一种选择是a在堆上分配:

int main(void)
{
   int rows,cols,*a,i;
   printf("Enter the number of rows: ");
   scanf("%d",&rows);
   printf("\nEnter the number of columns: ");
   scanf("%d",&cols);
   a = malloc(rows*cols*sizeof(int));
   for(i=0;i<rows*cols;i++)
   {
        a[i]=i+1;
   }
   print(rows,cols,a);
   getch();
   free(a);
}
Run Code Online (Sandbox Code Playgroud)

另请注意我:

  1. 添加了scanf()呼叫中丢失的&符号;
  2. 将返回类型更改main()int.请参阅C的main()函数的有效签名是什么?

正如您为什么代码不起作用:

传统上,C需要数组边界的常量表达式.当ROWSCOLS是常数,一切良好,你的代码.一旦你把它们变成变量,a就变成了一个可变长度的数组.问题是,该数组的大小在其中阵列被声明的点计算的,并在该点的值ROWSCOLS被尚未公知的.

在C99中,可以通过按下声明来修复代码a:

int main(void)
{
   int rows,cols,i;
   printf("Enter the number of rows: ");
   scanf("%d",&rows);
   printf("\nEnter the number of columns: ");
   scanf("%d",&cols);
   int a[rows*cols];
   for(i=0;i<rows*cols;i++)
   {
        a[i]=i+1;
   }
   print(rows,cols,a);
   getch();
}
Run Code Online (Sandbox Code Playgroud)