Exercise: Duplicate Input

Let's practice using malloc and free and solve the following exercise.

The input for your program will be a sequence of integers; the first integer is N, the count of numbers to read, and the following N numbers you must read into memory. Then print the numbers twice, one per line.

Example input:

5
1 2 3 4 5

Expected output for this input:

1
2
3
4
5
1
2
3
4
5

Note that if you use scanf, you don't really care how exactly the input numbers are arranged in the file: one number per string or multiple numbers per string; scanf will skip all whitespace.

Since you'll need to print the numbers twice, you need to store them somewhere, like in an array. But we cannot create an array of the unknown size, so our only option is to use malloc to allocate exactly as much memory as we need: after reading the first number (the count) we know that.

Assuming we read the count into a variable:

int count;

scanf("%d", &count);

Now we know that we expect count numbers after that, so we can allocate memory of the exact size for count numbers:

int count;
int *p;

p = malloc(count * sizeof(*p)); /* count times size of one value pointed to by p */

Then use p just like an array, and don't forget to free(p) when done.

Ready to write the code?

// 5
// 1 2 3 4 5
#include <stdio.h>
#include <stdlib.h>

int main() {
	/* your code here! */
  return 0;
}
© Alexander Fenster (contact)