0

I'm having trouble inputing values from the keyboard when I run my code. Everything compiles successfully, but when I go to run my code it prints out like this:

How many numbers would you like to place in the array: 7
Enter number 1: Enter number 2: 

etc, etc

Why is this happening? Also, is there a way to count and store the number of times that each element is in the array?

int main(void)
{

    int numbers = 0;
    int j = 0;
    char numStorage[j];
    int times = 0;
    char newArray[j];

    printf("How many numbers would you like to place in the array: ");
    scanf("%d", &numbers);

    j = numbers;

    int i = 1;

    while (i < (numbers + 1))
    {
        printf("Enter number %d: ", i);
        scanf("%c", &numStorage[i]);
        i++;
    }//close of while loop

    int x;

    for (x = 0; x < numbers; x++)
    {
        newArray[x] = numStorage[x];
    }//close of for loop

    int z;
    int q;

    for (z = 0; z < numbers; z++)
    {
        for (q = 0; q < numbers; q++)
        {
            if (numStorage[z] == numStorage[q])
            {
                times++;
                q++;
            }//close of if
            else
            {
                q++;
            }//close of else
        }//close of for loop

        printf("\n%d occurs %d times", numStorage[z], times);
        z++;
        q = 0;
        times = 0;
    }//close of for loop

}//end of main method
A.Coder
  • 51
  • 3
  • 8

1 Answers1

2

In

int j = 0;
char numStorage[j];

You declare numStorage as an array of characters with zero elements.

Then, in

int i=1;
while (i < (numbers + 1))
    {
        printf("Enter number %d: ", i);
        scanf("%c", &numStorage[i]);
        ..
     }

You're trying to allocate a character to numStorage[1] which is clearly out of bound access.

It should have been

 j = numbers;
 char numStorage[j];
 ...
 int i=0;
  while (i < numbers) # Array indices should be 0 to numbers-1

Edit

Reading characters using scanf after you've just read numbers(again using scanf) is also a problem and you should check [ this ] question for a workaround.

sjsam
  • 21,411
  • 5
  • 55
  • 102
  • 1
    This is also a problem, but the primary problem is that the newline is left behind after the number, so the first `"%c"` gets the newline without needing to wait for any input. – Jonathan Leffler Dec 01 '17 at 06:22
  • @JonathanLeffler Good note. I overlooked that point.. – sjsam Dec 01 '17 at 06:24