Can the size of an array be declared at runtime?

No. In an array declaration, the size must be known at compile time. You can’t specify a size that’s known only at runtime. For example, if i is a variable, you can’t write code like this: char array[i]; /* not valid C */ Some languages provide this latitude. C doesn’t. If it did, the stack would be more complicated, function calls would be more expensive, and programs would run a lot slower. If you know that you have an array but you won’t know until runtime how big it will be, declare a pointer to it and use malloc() or calloc() to allocate the array from the heap.  

Showing Answers 1 - 3 of 3 Answers

M. PAVAN KUMAR REDDY

  • Jan 18th, 2007
 

If you need this type of behavior, you have to use dynamic memory.

You can try this:

void main()

{

    int *ptr = NULL;

    int arr_size;

    printf("Enter the size of array : ");

    scanf("%d",&arr_size);

   ptr = (int*) malloc(arr_size*(sizeof(int));

}

Then you can use ptr as just like an array. If you wish to initialize array, you can initialize using ptr[0], ptr[1], ptr[2]....

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions