Hello, I wrote a program for I / O array with a given number of elements, but I do not know how to make the number of elements entered by the user.

#include <stdio.h> #include <stdlib.h> #include <conio.h> void input(int a[5]) { int i; for (i = 0; i < 5; i++) scanf("%d", &a[i]); } void output(int a[5]) { int i; for (i = 0; i < 5; i++) { printf("%d ", a[i]); } } int main() { clrscr(); int a[5]; printf("Print 5 elem mass: "); input(a); printf("Printed mass: "); output(a); getch(); return 0; } 

    1 answer 1

    Using a dynamic array. Something like

     int* input(int* num) { int i,n; printf("Input number of elements: "); scanf("%d",&n); int * a = malloc(n*sizeof(int)); for(i = 0; i < n; i++) { printf("a[%d] = ",i); scanf("%d", &a[i]); } *num = n; return a; } void output(int *a, int n) { int i; for(i = 0; i < n; i++) { printf("a[%d] = %d\n",i, a[i]); } } int main() { int n; int * a = input(&n); printf("Printed mass: "); output(a,n); free(a); getch(); return 0; } 
    • line does not work int * a = malloc (n sizeof (int)); can't convert void to int * - Dave Manston
    • So, you wrote a lie that in C. This is what is written in C ++, compiles to C without problems. Or compile as C, or add (int*) right before malloc ... Only if it were C ++ from the very beginning, would the code be different ... - Harry
    • int a; printf ("Input number of elements:"); scanf ("% d", & n); a = (int ) malloc (n * sizeof (int)); I just added it myself and earned it) thanks, but I write in C, but the standard is 92 years old - Dave Manston
    • Well, if the answer suits you - mark it as accepted ... - Harry
    • Thank you very much for your help, marked - Dave Manston