malloc an Array

Lab C Intermediate 20 points

Read n, allocate exactly n ints with malloc, read the numbers, print them doubled, then free the memory.

Input

Line 1: n. Line 2: n integers.

Output

One line.

Example

Input

4
1 2 3 4

Output

2 4 6 8
Sample input available Sample output available
Editor
C

Hints

malloc(n * sizeof(int)) allocates room for n ints.

Always free what you malloc.

Solution explanation

Heap memory lets the size be decided at runtime. Check for NULL in case allocation fails.

Show solution
#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    scanf("%d", &n);
    int *a = malloc(n * sizeof(int));
    if (a == NULL) return 1;
    for (int i = 0; i < n; i++) scanf("%d", &a[i]);
    for (int i = 0; i < n; i++) printf("%d%s", a[i] * 2, i < n - 1 ? " " : "\n");
    free(a);
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD