can i declare an array with a variable in C

March 25, 2010 at 07:02:08
Specs: Windows XP
is it allowed in C to declare an array with a variable like

int x;

printf("Enter the length of the array A: ");
scanf("%d",&x);

int A[x] = {0};

for(int i=0;i<x;i++)
{
          a[i] = i;
}
printf("\nthe array is as follows:");

for(int i=0;i<x;i++)
{
          printf("\n%d ",a[i]);
}


See More: can i declare an array with a variable in C

Report •

#1
March 25, 2010 at 07:58:51
Since it's plain C you will need to include stdlib.h and use malloc(if it were C++ then you would use "new").

    int *A = (int *)malloc(x * sizeof(int));
    if(A == NULL)
    {
         printf("Something went wrong - couldn't allocate memory");
         return 1;
    }

   //When you are finished with the array be sure ti
    //use free on it
    free(A)



Report •
Related Solutions


Ask Question