patha
patha

Reputation: 75

How can I make a 2-D array in C using user inputs

I tried to make a 2-D array given the numbers of rows and columns as the user input.

int main(void)
{
   int nx, ny;
   scanf_s("%d", &nx);
   scanf_s("%d", &ny);
   int array[nx][ny];
   return 0;
}

But VSC is telling me that I must have constants in the parenthesis [].

Is there any way I can convert 'nx' and 'ny' as constant?

Or is there any other way to declare 2-D or N-D arrays without converting their dtype?

Upvotes: 1

Views: 117

Answers (3)

Garampapa
Garampapa

Reputation: 11

This is would be a way of doing it:

int main(void)
{
   int nx=0, ny=0;#intialize some random values to the variable
   scanf_s("%d", &nx);
   scanf_s("%d", &ny);
   int array[nx][ny];
   return 0;
}

Upvotes: 1

Axifive
Axifive

Reputation: 1151

You should use malloc or for educational purposes declare MAX size matrix and work only within nx-ny region

#define MAX 1000
int main(void)
{
   int nx, ny;
   int array[MAX][MAX];
   scanf_s("%d", &nx);
   scanf_s("%d", &ny);
   if(nx > MAX || ny > MAX) return 1; // valid range check 
   // work with array
   return 0;
}

Upvotes: 0

paulsm4
paulsm4

Reputation: 121649

C99 introduced "Variable Length Arrays" ("VLAs"), but I would strongly discourage their use. Your best bet is to use good old malloc()

EXAMPLE:

https://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int r = 3, c = 4; //Taking number of Rows and Columns
    int *ptr, count = 0, i;
    ptr = (int *)malloc((r * c) * sizeof(int)); //Dynamically Allocating Memory
    for (i = 0; i < r * c; i++)
    {
        ptr[i] = i + 1; //Giving value to the pointer and simultaneously printing it.
        printf("%d ", ptr[i]);
        if ((i + 1) % c == 0)
        {
            printf("\n");
        }
    }
    free(ptr);
}

ADDENDUM:

MSVS might support VLAs in version 16.8 or higher: https://devblogs.microsoft.com/cppblog/c11-and-c17-standard-support-arriving-in-msvc/

Upvotes: -1

Related Questions