-4

So, I'm writing a program in C. I've to do 2 parts of it. one part deals with 1D arrays and the other deals with 2D arrays. THe program requirement is that we enter the size of the arrays through user input. Here's how I did it for the first one:

char* i; 
printf("\n\nHow many characters? ");  //takes input from user
scanf("%d",&num);
i = new char[num];

This worked.

Now when I do the same for 2D Arrays, it doesn't work. How to do it?

char* i; 
int numOfStrings,maxSize;       
printf("How many strings do you want to enter? ");
scanf("%d",&numOfStrings);
printf("What is the max size of the strings? ");
scanf("%d",&maxSize);

i = new char[numOfStrings][maxSize];    
  • `new char` what?? you want C or C++ ? – Avezan Jun 10 '18 at 22:03
  • I want it to be in C – Momin Naqvi Jun 10 '18 at 22:04
  • 2
    look for `malloc` and `calloc` on internet... there is no `new` in C, its a C++ thing.. – Avezan Jun 10 '18 at 22:05
  • Then can you please write the code for of these in C? 1D and 2D? Searching would take time and I don't have that right now. – Momin Naqvi Jun 10 '18 at 22:07
  • I dont think stackoverflow works that way.. https://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/ – Avezan Jun 10 '18 at 22:08
  • @Avezan Please don't recommend incorrect trash tutorials on other sites, when we have correct tutorials here on SO. In this case [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays). Overall, avoid "geeks for geeks", the quality of that site is often very low. – Lundin Jun 11 '18 at 09:31

1 Answers1

3

If the numbers are reasonably small, you can use C99 array definitions:

printf("\n\nHow many characters? ");  //takes input from user
if (scanf("%d", &num) != 1)
    return 1;
char i[num];

The same for a 2D array:

int numOfStrings, maxSize;
printf("How many strings do you want to enter? ");
if (scanf("%d", &numOfStrings) != 1)
    return 1;
printf("What is the max size of the strings? ");
if (scanf("%d", &maxSize) != 1)
    return 1;

char i[numOfStrings][maxSize];

Note however that i is a very confusing name for an array, let alone a 2D array.

chqrlie
  • 131,814
  • 10
  • 121
  • 189