简体   繁体   中英

Initialising a variable 2-D array with a specific value

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).

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++.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM