Exception Thrown at 0x796BF2F0. Don't understand how to fix it

0

I get an error saying "Exception thrown at 0x796BF2F0 (ucrtbased.dll) in Chapt 14.exe: 0xC0000005: Access violation reading location 0x00000000." How do I fix this?? I put inside of the code where I get the error. I don't know how to break it or fix it. If someone could please help me out that would be fantastic!

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

//initialize main

int main(int argc, char* argv[])

{

    //define variables

    int size = 10;
    int numArray[10];

    int i, j;
    int temp;
    srand((unsigned)time(0));

    //to generate 10 random numbers in the array

    for (i = 0; i < size; i++)

    {

        //generate random values between 1 to 100
        //store numbers in variable numArray

        numArray[i] = 1 + rand() % 100;

    }

    //sort array based on entry

    // if argument is -a or -A sort ascending

    if ((strcmp(argv[1], "-a") == 0) || (strcmp(argv[1], "-A") == 0)) {

        //This Logic will Sort the Array of elements in Ascending order
        for (i = 0; i < size; i++) {
            for (j = i + 1; j < size; j++) {
                if (numArray[i] > numArray[j]) {
                    temp = numArray[i];
                    numArray[i] = numArray[j];
                    numArray[j] = temp;
                }
            }
        }

    }

    //if argument is -d or -D
    else if ((strcmp(argv[1], "-d") == 0) || (strcmp(argv[1], "-D") == 0)) ***I have the error here***

    {
        //This Logic will Sort the Array of elements in Ascending order
        for (i = 0; i < size; i++) {
            for (j = i + 1; j < size; j++) {
                if (numArray[i] < numArray[j]) {
                    temp = numArray[i];
                    numArray[i] = numArray[j];
                    numArray[j] = temp;
                }
            }
        }

    }

    //print stored array

    printf("\n\nThe sorted array is: \n");

    //loop to print every element of array

    for (i = 0; i < size; i++)

    {

        //Display output
        printf("%d\t", numArray[i]);

    }
    return 0;

}
c
asked on Stack Overflow Nov 30, 2020 by alexis1234

1 Answer

0

You're invoking the program without command line parameters, therefore argv[1] is NULL and therefore strcmp(argv[1], ... crashes.

Change your code like this:

...
int main(int argc, char* argv[])
{
  if (argc < 2)
  {
    printf("Not enough command line arguments\n");
    exit(EXIT_FAILURE);
  }

  //define variables
  ...

and invoke the program with appropriate command line parameters.

answered on Stack Overflow Nov 30, 2020 by Jabberwocky

User contributions licensed under CC BY-SA 3.0