Search code examples
cvisual-studio-codeexedev-c++geany

.exe file closing abruptly outside code editor


So I compiled and ran the following C program:

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

int main()
{
    int **p,n,i,j,trace=0;
    printf("Enter the order of the square matrix\n");
    scanf("%d",&n);
    p = (int**)malloc(n*sizeof(int*));
    for(i=0;i<n;i++)
    *(p+i) = (int *)malloc(n*sizeof(int));
    for(i=0;i<n;i++)
    for(j=0;j<n;j++)
    {
        printf("Enter the element in row number %d and column number %d\n",i+1,j+1);
        scanf("%d",*(p+i)+j);
    }
    printf("The input matrix is \n");
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            printf("%d\t",*(*(p+i)+j));
            if(i==j)
            trace += *(*(p+i)+i);
        }
        printf("\n\n\n");
    }
    printf("The trace of given matrix is %d",trace);
    return 0;
}

It is running perfectly fine irrespective of whether I use Geany or Dev C++ or VS code, when I use the run command inside the editor.

It also runs fine if I open cmd, then change the directory to the directory containing the file and then run this.

However when I click on the .exe file directly in windows explorer, it closes abruptly after taking input, without showing the output. Any idea what's the problem?


Solution

  • Because once all command are executed, the terminal close itself.

    #include <stdio.h>
    #include <stdlib.h> /*
    #include <conio.h>  */ //remove comment markers if using getch() instead of getchar(),
                           //otherwise don't use it. It might not compile on some compilers
    int main() {
        int **p,n,i,j,trace=0;
        printf("Enter the order of the square matrix\n");
        scanf("%d",&n);
        p = (int**)malloc(n*sizeof(int*));
        for(i=0;i<n;i++)
        *(p+i) = (int *)malloc(n*sizeof(int));
        for(i=0;i<n;i++)
        for(j=0;j<n;j++)
        {
            printf("Enter the element in row number %d and column number %d\n",i+1,j+1);
            scanf("%d",*(p+i)+j);
        }
        printf("The input matrix is \n");
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                printf("%d\t",*(*(p+i)+j));
                if(i==j)
                trace += *(*(p+i)+i);
            }
            printf("\n\n\n");
        }
        printf("The trace of given matrix is %d",trace);
    
        printf("Enter any key and enter to continue...");
        getchar();   //_getch(); does not belong to standard library. use conio.h header at top
        return 0;
     }
    

    I have added getchar() at end which will read a value and close the terminal once you press enter key. getch give functionality of ending program with any key but does not belong to standart library. use conio.h header if using getch.