I need to create an array of integers with the aim of using them one by one later in the program. Integers are inputted by the user, so the size of the array and the size of each integer aren't constant. All I can say that due to specification of the program the array would not exceed, let's say, 100 elements and an integer would always be between 0 and 99. How can I do this? I am new to C and this is really baffling to me, as this is very easy to do in Python, and I've spent quite some time already trying to figure out how to make this work (I understand that all those complications with arrays arise from the fact that C is an old language).
1 Answer
First, don't confuse an integer value with the size of the type used to represent it. The values 0 and 99 will take up exactly the same amount of space in whatever integral type you use.
As for the array itself, you have several options available.
You can pick a meximum number of elements that your user won't be allowed to exceed:
#define MAX_ALLOWED 100
int main( void )
{
int values[MAX_ALLOWED]; // declare array with max-allowed values
size_t howMany;
// get howMany from user, make sure it doesn't exceed MAX_ALLOWED
...
}
If you are using a C99 or C2011 compiler that supports variable-length arrays, you could get the array length from the user and use that value in the array declaration:
int main( void )
{
size_t howMany;
// get howMany from user
int values[howMany]; // declare array with user-specified number of values
...
}
If you don't want to use VLAs (and there are some good reasons why you don't), you can use dynamic memory management routines:
#include <stdlib.h>
int main( void )
{
size_t howMany;
// get howMany from user
int *values = malloc( howMany * sizeof *values ); // dynamically allocate
// space to store user-
// specified number of
// values.
if ( !values )
{
// memory allocation failed, panic
exit( 0 );
}
...
free( values ); // release the memory when you're done.
}
Note that in the last case, values is not declared as an array of int, but a pointer to int; it will store the address of the memory that was dynamically allocated. You can still use the [] operator to index into that space like a regular array, but in many other respects it will not be treated the same as an array.
Regardless of how you create the array, assigning elements is the same:
for ( size_t i = 0; i < howMany; i++ )
{
values[i] = value_for_this_element();
}
realloc()function.int numbers[100];which will store up to 100 numbers of the range you want. Also declare a variable for example,int count=0;so you know how many elements of the array you have used. Once you have that working, you can explore the more complex method of memory allocation.if ( input < 0 || input > 99 ) { /*bug the user to reenter*/}int nums[100];up front. 400 bytes of memory is nothing to worry about and it makes it easier for the programmer.