简体   繁体   中英

VS Code C program is running but not showing anything

I am trying to run the c program on my vs code. I have code runner and c/c++ extension installed in vs code. Whenever I try to run the program it's always running not showing any output or result of my program.

It's happening with this specific code.

#include<stdio.h>
int main()
{
    int a[10],i,j,temp,n;
    printf("\n Enter the max no.of Elements to Sort: \n");
    scanf("%d",&n);
    printf("\n Enter the Elements : \n");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=0; i<n; i++)
        for(j=i+1; j<n; j++)
        {
            if(a[i]>a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    for(i=0; i<n; i++)
    {
        printf("%d\t",a[i]);
    }
    return 0;
}

Here you can see what's the problem. It's running for 2-3 min but not showing any output.

[Running] cd "c:\\Users\\rakib\\Downloads\\code" && gcc labreport.c -o labreport && "c:\\Users\\rakib\\Downloads\\code"labreport

You are creating an array of size 10 on the stack

int a[10];

But then you ask the user to enter how many elements they want to sort. If the user wants to sort more than 10 elements then your code would crash since your array only has enough space for 10 integers. To solve the problem you would need to use a dynamic array and allocate it on the heap.

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

Don't forget to include malloc.h library and to free the array when you are finished using it

free(a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM