-4

I've tried to make custom array size by:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x;
    int y;

    printf("Array size:");
    scanf("%d %d", &x, &y);

    int kancelar[x][y];
    int i;
    int q;

    for (q = 0; q < x; q++)
        for (i = 0; i < y; i++)
            kancelar[q][i] = getchar();

    for (q = 0; q < x; q++)
        for (i = 0; i < y; i++)
            putchar(kancelar[q][i]);

    return 0;
}

But no luck, values were wrong. I'm using C,

chqrlie
  • 131,814
  • 10
  • 121
  • 189

2 Answers2

1

You are getting messed up by the newlines present in the input buffer by the press of the Enter key after each input. You need to consume the newline each time before going for the getchar().

A simple solution may look like

printf("Array size:");
scanf("%d %d%*c",&x,&y);  //eat up the newline
int kancelar[x][y];
int i;
int q;
for(q = 0;q < x;q++)
{
    for(i = 0;i < y;i++ )
    {
        kancelar[q][i] = getchar();
        getchar(); //eat up newline
    }

}
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0
scanf("%d %d",&x,&y);
int kancelar[x][y];

You cannot create an array with variable values, you can do this with only constant values. So to create a custom array you need to allocate memory for you array dynamically

I have taken this code from this link : LINK

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int r, c;
    scanf("%d %d",&r,&c);

    // allocating memory
    int *arr = (int *)malloc(r * c * sizeof(int));

    int i, j, count = 0;
    // giving them default values
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         *(arr + i*c + j) = ++count;

    // printing the values 
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%d ", *(arr + i*c + j));

   // free memory
   free(arr);

   return 0;
}

Check out the link as they show more than one ways to achieve this

Yousuf Azad
  • 414
  • 1
  • 7
  • 17
  • 3
    yes you can, it is called VLA i.e. if you have a C99 compiler (or later) https://en.wikipedia.org/wiki/Variable-length_array – AndersK Feb 06 '16 at 14:05
  • 1
    1)Remove the cast from `malloc` as it is unneccessary 2)Declare `r` and `c` 3)`free` the allocated memory – Spikatrix Feb 06 '16 at 14:24
  • @AndersK. Did not know that. – Yousuf Azad Feb 06 '16 at 14:48
  • @CoolGuy Thanks! about #1 malloc returns void pointer, don't we need to cast it first? [malloc reference](http://www.cplusplus.com/reference/cstdlib/malloc/) – Yousuf Azad Feb 06 '16 at 14:53
  • @sami1592 `void*` is automatically converted. Read [Do I cast the result of malloc?](http://stackoverflow.com/q/605845/3049655) – Spikatrix Feb 06 '16 at 15:04