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; } 
0

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@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.
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.
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); 

2 Comments

The OPs code is valid in more recent extensions of the C spec, and doing this is preferred to malloc where available.
Please qualify "you cannot allocate a dynamic array in C" in your answer. It is perfectly valid C99 code. Thanks.
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 { //... } 

Comments

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

Comments

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.

3 Comments

YOU mean to say that if i will write like int size=5;
but it still doen't work for me,& please read the code carefully,i am assigning a constant value To my variable SIZE,
@Alfred Nobel: try const int size = 5 or #define size 5 (the former is typically preferred)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.