cfault

Segmentation fault: 11, in C code when trying to print results


I am writing a program in C that will do some logic, but at the moment i am just trying to test that the inputs are being saved correctly. str is supposed to store one of the menu options listed, the unsigned int hex is supposed to store a hex value, and the int is storing a decimal value.

Below is the code:


int main()
{
  char str[2];
  unsigned int hex;
  int decimal;

  printf("Choose an Option (C, M, Q, S, V): ");
  scanf("%s", &str);

  printf("Enter a value for x: ");
  scanf("%u", &hex);

  printf("Enter a value for n: ");
  scanf("%d",decimal);

  printf("Testing: %s, %u, %d\n",str,hex,decimal);
  return 0;
}

When I compile it on my terminal it gives me no errors, and it even runs through all the inputs i ask of it. The output looks like this:

Enter a value for x: 1
Enter a value for n: 1
Segmentation fault: 11

Why am I getting segmentation fault 11? Any help is appreciated.


Solution

  • & is not needed here:

    scanf("%s", &str);
    

    And & is needed here:

    scanf("%d",decimal);