Can the size of an array be declared at runtime?


Levels of difficulty: / perform operation:

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.

If you know at compile time how big an array is, you can declare its size at compile time. Even if the size is some complicated expression, as long as it can be evaluated at compile time, it can be used.

#include<stdio.h>
#include <malloc.h>
#include<conio.h> 
int main(int argc, char** argv) {
	char** new_argv;
	int i;
	/* Since argv[0] through argv[argc] are all valid, the
    program needs to allocate room for argc+1 pointers. */
	new_argv = (char**) calloc(argc+1, sizeof (char*));
	/* or malloc((argc+1) * sizeof (char*)) */
	printf("allocated room for %d pointers starting at %P\n", argc+1, new_argv);
	/* now copy all the strings themselves
    (argv[0] through argv[argc-1]) */
	for (i = 0; i < argc; ++i) {
		/* make room for '' at end, too */
		new_argv[i] = (char*) malloc(strlen(argv[i]) + 1);
		strcpy(new_argv[i], argv[i]);
		printf("
		allocated %d bytes for new_argv[%d] at %P, "
		"
		copied \"
		%s\"
		\n"
		,
						                strlen(argv[i]) + 1, i, new_argv[i], new_argv[i]);
	}
	new_argv[argc] = NULL;
	/* To deallocate everything, get rid of the strings (in any
    order), then the array of pointers. If you free the array
    of pointers first, you lose all reference to the copied
    strings. */
	for (i = 0; i < argc; ++i) {
		free(new_argv[i]);
		printf("
		freed new_argv[%d] at %P\n"
		, i, new_argv[i]);
		argv[i] = NULL;
	}
	free(new_argv);
	printf("
	freed new_argv itself at %P\n"
	, new_argv);
	return 0;
}