0

I am trying to write a program that can create an array with size based on user input.

How do I create an array with size based on the user input?
This is what I have so far:

printf("Enter the number of chars needed in the array: ");
int size;
scanf("%d", &size);
char char_array[size];
2

1 Answer 1

1

Congratulations on starting to learn, are you following a tutorial of some sort? The next thing you should be learning about is dynamic memory allocation, as opposed to static allocation (size known at compile time) on the stack.

From that Wikipedia page's examples:

Creating an array of ten integers with automatic scope is straightforward in C:

int array[10];

However, the size of the array is fixed at compile time. If one wishes to allocate a similar array dynamically, the following code can be used:

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

Obviously for your case, replace int with char and 10 with size.

And always (this is the tricky thing about dynamic allocation) remember to free() any memory you have malloced once you're finished with it!

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

2 Comments

From that same wiki page: "C99 offered variable-length arrays as an alternative stack allocation mechanism - however, this feature was relegated to optional in the later C11 standard." Which is 7 years old, now, and can be considered "current": "This new version mainly standardizes features that have already been supported by common contemporary compilers" (en.wikipedia.org/wiki/C11_(C_standard_revision))
@usr2564301 that's correct, so "current" compilers are no longer required to support VLAs. Sounds like a good reason to avoid them!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.