5

I have written a following code (see code comments for the question),

#include<stdio.h>
int main()
{
    int size;
    scanf("%d",&size);
    int arr[size];    /*is it a valid statement?*/
    for(int i=1;i<=size;i++)
    {
        scanf("%d",&arr[i]);
        printf("%d",arr[i]);
    }
    return 0;
}
Phonon
  • 12,549
  • 13
  • 64
  • 114
nobalG
  • 4,544
  • 3
  • 34
  • 72

5 Answers5

6

The use of a non constant array size is valid C99 but not C90. There is an older gcc extension allowing it.

Note that taking advantage of this make it harder to check that memory allocation succeed. Using it with values provided by the user is probably not wise.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143
  • 1
    @Alfred Nobel: In short, no; you cannot declare an array in this manner with a length determined at runtime. In C++, `size` would have to be declared `const` and initialized with an integer constant expression (i.e., a numeric literal); IOW, it would have to be known at compile time. – John Bode Apr 13 '11 at 17:20
  • No (usually you'll use an std::vector) and it hasn't been imported in C++0X like some other C99 features have. ISTR that g++ has inherited the gcc extension. – AProgrammer Apr 13 '11 at 17:45
4

You cannot allocate a dynamic array in C90 like that. You will have to dynamically allocate it with malloc like this:

int* array = (int*) malloc(sizeof(int) * size);

You also index the arrays starting at 0 not 1, so the for loop should start like this:

for(int i = 0; i < size; i++)

If you use the malloc method, you will also need to free the memory after you're done with it:

free(array);
DShook
  • 14,833
  • 9
  • 45
  • 55
  • 1
    The OPs code is valid in more recent extensions of the C spec, and doing this is preferred to `malloc` where available. – JSBձոգչ Apr 13 '11 at 16:37
  • Please qualify "you cannot allocate a dynamic array in C" in your answer. It is perfectly valid C99 code. Thanks. – NPE Apr 13 '11 at 16:38
3

Also,

Array indexing in C starts for 0, not from 1. and does not include the size.

int i;
for(i=0 ; i < size ; i++) // Notice the < and the 0
{
     //...
}
0

The compiler tries to evaluate int arr[size] at compile time. In this case, arr is allocated on the stack, so the compiler wants to know its size ahead of time. Instead, you need to allocate arr on the heap using malloc, like this.

#include<stdio.h>
int main()
{
    int size;
    scanf("%d",&size);
    int *arr = malloc(sizeof(int) * size);
    for(int i=1;i<=size;i++)
    {
        scanf("%d",&arr[i]);
        printf("%d",arr[i]);
    }

    free(arr);
    return 0;
}

See this post for more information on when to use malloc

Community
  • 1
  • 1
Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
0

This would be valid if size were constant. Otherwise, you should do what DShook said. Additionally, make sure you free(array) at some point, or your program will leak memory.

Zach Rattner
  • 20,745
  • 9
  • 59
  • 82