my code outputs less numbers than it should

0 votes
asked Oct 20 by KeunwonChoi (120 points)
#include <stdio.h>

int main()
{
    int size=0;
    int arr[size];
    
    printf("input size of array: ");
    
    scanf("%d",&size);
    
    printf("\ninput elements of array: ");
    
    for(int i=0;i<size;i++)
    {
        scanf("%d",&arr[i]);
    }
    
    
    printf("\nThe array  is ");
    
    for(int i=size;i>0;i--)
    {
        printf("%d ",arr[i-1]);
    }
    
    return 0;
}

This is my code that I'm trying to practice.

It should get the user input a single number -> make that the size of an array.

Get a second user input which defines the elements of the array

And then it should print it in reverse order.

Basically it works fine,

but when i input 9 / 1 2 3 4 5 6 7 8 9

the output should be 9 8 7 6 5 4 3 2 1.

but it just does : 6 5 4 3 2 1 / only 6 digits.

I did not contain anything that restrict the output. But I can't figure out what is wrong.

1 Answer

0 votes
answered Oct 22 by Peter Minarik (12,220 points)

The Problem

Your array is defined with a size 0.

int size=0;
int arr[size];

Later on, you read size, but at that point arr is already initialised.

The error happens when you actually try to write this array:

scanf("%d",&arr[i]);

Every such call is writing to memory that does not belong to you (remember, your array's size is 0).

The Solution

You can declare and define your array after you've read size.
int main()
{
    int size=0;
    printf("input size of array: ");
    scanf("%d",&size);
    int arr[size];
    // ...
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...