C++ : Creating an array with a size entered by the user
In C++, there are two types of storage: stack-based memory, and heap-based memory. The size of an object in stack-based memory must be static (i.e. not changing), and therefore must be known at compile time. That means you can do this:
int array[10]; // fine, size of array known to be 10 at compile time
but not this:
int size;
// set size at runtime
int array[size]; // error, what is the size of array?
Note there is a difference between a constant value and a value known at compile time, which means you can't even do this:
int i;
// set i at runtime
const int size = i;
int array[size]; // error, size not known at compile time
If you want a dynamically-sized object, you can access heap-based memory with some form of the new
operator:
int size;
// set size at runtime
int* array = new int[size] // fine, size of array can be determined at runtime
However, this 'raw' usage of new
is not recommended as you must use delete
to recover the allocated memory.
delete[] array;
This is a pain, as you have to remember to delete
everything you create with new
(and only delete
once). Fortunately, C++ has many data structures that do this for you (i.e. they use new
and delete
behind the scenes to dynamically change the size of the object).
std::vector
is one example of these self-managing data structures, and is a direct replacement for an array. That means you can do this:
int size;
// set size at runtime
std::vector<int> vec(size); // fine, size of vector can be set at runtime
and don't have to worry about new
or delete
. It gets even better, because std::vector
will automatically resize itself as you add more elements.
vec.push_back(0); // fine, std::vector will request more memory if needed
In summary: don't use arrays unless you know the size at compile time (in which case, don't use new
), instead use std::vector
.
How to take array size of length as user input?
Yeah, in C you couldn't create variable-sized array, and variable-sized in this context means that you can't create array when it's size isn't constant on the compile time. But you can use pointers, and after user input you can allocate array with the appropriate length.
For example:
int* array;
int length;
printf("Enter length of the array: ");
scanf("%d", &length);
// maybe you need to add checking, like if length > 0
array = malloc(sizeof(int) * length);
// now you have array with `length` elements and 0..`length`-1 indexes
Does specifying array size for a user input string in C matter?
When you declare an array of char
as you have done:
char str[10] = "Jessica";
then you are telling the compiler that the array will hold up to 10
values of the type char
(generally - maybe even always - this is an 8-bit character). When you then try to access a 'member' of that array with an index that goes beyond the allocated size, you will get what is known as Undefined Behaviour, which means that absolutely anything may happen: your program may crash; you may get what looks like a 'sensible' value; you may find that your hard disk is entirely erased! The behaviour is undefined. So, make sure you stick within the limits you set in the declaration: for str[n]
in your case, the behaviour is undefined if n < 0
or n > 9
(array indexes start at ZERO). Your code:
printf("%c\n", str[15]);
does just what I have described - it goes beyond the 'bounds' of your str
array and, thus, will cause the described undefined behaviour (UB).
Also, your scanf("%s", &str);
may also cause such UB, if the user enters a string of characters longer than 9 (one must be reserved for a terminating nul
character)! You can prevent this by telling the scanf
function to accept a maximum number of characters:
scanf("%9s", str);
where the integer given after the %
is the maximum input length allowed (anything after this will be ignored). Also, as str
is defined as an array, then you don't need the explicit "address of" operator (&
) in scanf
- it is already there, as an array reference decays to a pointer!
Hope this helps! Feel free to ask for further clarification and/or explanation.
How to define array size based upon number of inputs?
Starting with C99 you can use variable-length arrays. You can declare them as you go, using a size_t
variable for its size.
size_t n;
printf("How many numbers would you like to enter?\n");
scanf("%zu", &n);
int array[n];
for (size_t i = 0 ; i != n ; i++) {
printf("Enter number %zu: ", i+1);
scanf("%d", &array[i]);
}
printf("You entered: ");
for (size_t i = 0 ; i != n ; i++) {
printf("%d ", array[i]);
}
printf("\n");
Demo.
Note : This approach works for relatively small arrays. If you anticipate using larger arrays, do not use this approach, because it could lead to undefined behavior (overflowing the automatic storage area). Instead, use malloc
and free
.
How to create an array without knowing the size in c language
You can create a dynamic array by following the answer to this question. It uses a structure that contains the array, its max size and its used size. If the max size is reached, the array will be reallocated and the max size increased.
C User input size of Array
You should use malloc to dynamically allocate the size of array
#include <stdlib.h>
int main()
{
struct inventoryItem *inventory; //use pointer to item
printf("Enter the number of slots needed in the array: ");
int size;
scanf("%d", &size);
//after you get the size input
inventory = malloc(sizeof(struct inventoryItem)*size);
}
In the end you should use the free
to free the memory
Related Topics
Isn't the Const Modifier Here Unnecessary
How to Obtain C++ Type Names in a Constexpr Way
How to Read from a Version Resource in Visual C++
Create an Application Without a Window
What Happens When You Deallocate a Pointer Twice or More in C++
How to Initialize Std::Vector Over Already Allocated Memory
Printing Values of All Fields in a C++ Structure
Why Reference Size Is Always 4 Bytes - C++
Acquire/Release Semantics with Non-Temporal Stores on X64
Preventing Compiler Optimizations While Benchmarking
What Does This Variadic Template Code Do
C++ Template Friend Operator Overloading
How to Pass Std::String to a Dll
What Is the Maximum Length in Chars Needed to Represent Any Double Value