ferocioussprouts
ferocioussprouts

Reputation: 27

How do I print an int array of unknown size?

I would like to know how to print an int array of an unknown size in C (not C++). I don't know the number of user inputs, but I know that it is at most 1000. The user inputs a bunch of integers. I need to print out the integers that have an even position. My plan is to store the integers that have an even position in an int array and print it. But I'm stuck as I have no idea about the size.

Upvotes: 0

Views: 1587

Answers (1)

Yun
Yun

Reputation: 3812

For statically allocated arrays, you can divide the total size (in bytes) by the size of one element (in bytes):

int array[512];
size_t arraySize = sizeof(array) / sizeof(*array) // = 512

For dynamically allocated arrays, you'll have to manually keep track of the size. That means, storing the size when the array is created and updating that value if the array is reallocated.

From the question and comments, I gathered that you would like to read the integers from stdin (until EOF, I presume). There are several way of doing this:

1. Allocate an array of the maximum size and print every other element

int array[1000];
size_t size = 0;
while (scanf("%d", &array[size]) != EOF)
    ++size;

for (size_t idx = 0; idx < size; idx += 2)
    printf("%d\n", array[idx]);

2. Allocate half of the maximum size and store every other element

Since not all elements are used in the output, we may as well store only the ones we need. Use the * in the scanf format specifier to discard the second integer.

int array[500];
size_t size = 0;
while (scanf("%d%*d", &array[size]) != EOF)
    ++size;

for (size_t idx = 0; idx < size; ++idx)
    printf("%d\n", array[idx]);

3. Allocate the minimum amount of memory

Every time we need to store another integer, we increase the size of the array by 1. This is space efficient, but not very fast.

int *array = NULL;
size_t size = 0;
int n;
while (scanf("%d%*d", &n) != EOF)
{
    array = realloc(array, ++size * sizeof *array);
    array[size - 1] = n;
}

for (size_t idx = 0; idx < size; ++idx)
    printf("%d\n", array[idx]);

free(array);

4. Not storing an array at all

Noticing that the output doesn't depend on having read the entire array, we may as well print the first of every two integers. This won't look pretty in the terminal if the program is interactive (i.e. the user types the integers while the program is running), but will work fine if it receives its input from stdin.

int n;
while (scanf("%d%*d", &n) != EOF)
    printf("%d\n", n);

For all code, the usual warnings about using scanf and checking the return value of realloc apply.

Upvotes: 3

Related Questions