-2

I have a problem with my code. It should take from user amount of numbers in array and user should write the number he wants in range 1-100.

Also the program should display the smallest and the highest number. If I want to have an array with more than 7 numbers, it crashes down while I type in the numbers.

Every time when it comes to the number 7, program crashes. I have no idea why it isn't working.

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

int n, i, a;
int main ()
{
    int tab[n];

    printf("\nhow many elements you want to have?\n");
    do
    {
        scanf ("%d", &n);
        if ((n>30 || n<1))
            printf("\ntoo high or too low\n");          
    }
    while ((n<1 || n>30));
    printf("\nyour number please:\n");
    for(i = 0; i < n; i++)
    {
        do
        {
            printf("\nelement %d:", i+1);
                scanf("%d", &a);
            if ((a < 1 || a > 100))
                printf("\nnumber too high or too low\n");
            tab[i]=a;
        }
        while((a < 1 || a > 100));
    }
    printf("\nyour numbers:");
    for (i=0; i<n; i++)
    {
        printf("\n%d", tab[i]);
    }

    int min = tab[0];
    int max = tab[0];
    for (i = 0; i<n; i++)
    {
        if (tab[i]> max)
        max = tab[i];
        if(tab[i]< min)
        min = tab[i];
    }
    printf("\nsmallest: %d", min);
    printf("\nbiggest: %d", max);
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
wolfdogg
  • 11
  • 3

3 Answers3

1

The problem here is this declaration:

int tab[n];

You are declaring a variable length array (available since C99) with an uninitialized value as the length. I understand that you want to make room for the numbers that you are going to store from stdin but that's not the proper way to do it.

I see two solutions:

  • the easy one, choose a maximum fixed amount of numbers (which is the case in your situation since you allow a maximum of 30 values) and change the declaration to int tab[30]
  • use dynamically allocated memory, for example take a look here
Community
  • 1
  • 1
Jack
  • 131,802
  • 30
  • 241
  • 343
0

If you add printf("%d",sizeof tab); after the declaration int tab[n], the program will output 0.

You wrote int n; outside main(), making it a global variable, which is initialized to zero by default, but you didn't give it any other value before using it in the statement int tab[n];, so it's equal to int tab[0] in your case.

To use VLA, you must declare tab[n] after n is given by the user.

This error causes undefined behavior, allowing anything to happen. Thus, your program can crash when you input the second number, or it will never crash, if you are really (un)lucky. Number 7 doesn't have any magic power.

nalzok
  • 14,965
  • 21
  • 72
  • 139
-1

you have to specife your array length in C

tab[100];
Anivia
  • 53
  • 2
  • 7
  • 1
    Please do some research and learn about *variable length arrays* before writing factually incorrect answers. – fuz Jan 19 '16 at 01:54