Initialising a variable 2-D array with a specific value

179 views Asked by At

I know that we can initialize a 2-D array with 0 by writing

a[value_1][value_2] = {0};

and if we write

a[value_1][value_2] = {number other than 0};

the first element get initialized by the number given in { } and rest all by 0.

But, the thing bugging me is that how can we initialize an array whose parameters value_1 and value_2 have been taken input from the user as it shows the error that variable sized object may not be initialized.

Also, it will be helpful if you can also tell the same about multidimensional array(instead of just 2 dimensional array).

2

There are 2 answers

3
nickie On

To do this in C99 (compile with gcc -std=c99):

#include <stdio.h>
#include <string.h>

int main ()
{
  int value_1, value_2;
  scanf("%d %d", &value_1, &value_2);

  int a[value_1][value_2];

  // initialize
  for (int i=0; i<value_1; i++)
    for (int j=0; j<value_1; j++)
      a[i][j] = 0;
  // or
  memset(a, 0, value_1*value_2*sizeof(int));

  return 0;
}

In C++, variable length arrays are not supported, as @JensGustedt pointed out. On the other hand, g++ supports it, so the same code above will work there too.

As far as I know, initializers in variable sized objects are not supported, either in C or in C++.

3
nikoo28 On

You cannot initialize the array using values input by the user. C does not allow this.

Refer to Dennis Ritchie.

One way to achieve the same thing can be done by using the malloc() function.

#include<stdio.h>
#include<malloc.h>

int main(void)
{
    int limit;
    printf("Enter the array limit:- ");
    scanf("%d",&limit);
    int *arr = (int*)malloc(sizeof(int) * limit);

    // The above statement allocates the memory equivalent to 3 integers

    // Now considering your limit is 3 and initializing values

    arr[0] = 43;
    arr[1] = 65;
    scanf("%d",&arr[2]);    // All of these work perfectly fine.

    return 0;
}

I hope this helps. Same way you can create multi-dimensional arrays as well. There is no explicit way to define the limit in standard C. You cannot do int arr[limit];