I try as follows:

int main() { int n; int i; printf("Enter elements", n); scanf("%d", &n); int* a = malloc(n * sizeof(int)); for (i = 0; i < n; i++) { printf("a[%d] = ", i); scanf("%d", &a[i]); } for (i = 0; i < n; i++) printf("%d ", a[i]); getch(); return 0; } 

The compiler gives the following error:

Error 2 error C2440: 'initializing': cannot convert from 'void *' to 'int *'

    2 answers 2

    You compile a program like C ++, not like C. If you compiled it like C, then the cast

     int * a = (int*)malloc(n * sizeof(int)); 

    would be unnecessary. See for yourself .

    More - why are you here n

     printf("Enter elements", n); 

    if you don't use it?

    • And the truth is ... n do not need here ... Thank you! - Vladislav Maslov
    • I can’t figure it out with a compilation in C or C ++ ... On pairs, they showed me how to create a file to write on C ... So I create ...))) - Vladislav Maslov
    • Usually it is enough to ask him the extension .c, and not .cpp :) - the compilers are smart enough. There is also a configuration with the appropriate command line parameter or in the project properties in the IDE. - Harry
    • Thank you very much! - Vladislav Maslov

    It turned out to solve the problem!

    Replaced

    int * a = malloc(n * sizeof(int));

    on

    int * a = (int*) malloc(n*sizeof(int));

    And at the end he cleared the memory with free(a);

    • Congratulations on your decision! - kitscribe