Segmentation fault error when working with arrays in C

  arrays, c++, out-of-memory, segmentation-fault

Segmentation fault error when working with arrays in C

When I compile my code is doesn’t give me any errors however when I run it, I get the following error:
1
The result should look like this instead:
2

My code is supposed to “encrypt” a number by returning the location of the number from a random generated array of numbers from 0 to 9

Here’s my code:

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

void swap (int a[], int n)
{
    int position1, position2;
    int i, j; 
    srand (time(NULL));

   //creates two random positions and swaps the numbers
    for (i=0; i<10; i++){
        position1 = rand()%10;
        position2 = rand()%10;

        j= a[position1];
        a[position1] = a[position2];
        a[position2] = j;
    }
    //displays the numbers
    for (i= 0; i < n; i++){
        printf("%d  ", a[i]);
  }
} 

void replace (int a[], int b[], int key[], int n)
{
   //encrypts the number by replacing the number with the position on the array
    int i;                         
    for (i =0; i<n; i++){
      b[i] = key[a[i]];
    }
}

int main()
{
    //initializes the arrays 
    int a[10], b[10], key[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, n;

    //asks the user for input 
    printf ("Enter the number of digits in the numbers: ");
    scanf ("%d", &n); 

    printf("Enter the number: ");
    int i; 
    for (i=0; i<n; i++); {
        scanf("%1d", &a[i]);
    }

    //Calls swap function and displays the array
    swap(key,10);

    printf("Key array: ");
    for (i=0; i<10; i++){
        printf("%1d   n", key[i]);
    }

    //calls the replace function
    replace(a, b, key, n);

    //prints encrypted number
    printf("Output: ");

    for (i=0; i<n; i++){
      printf("%1d ", b[i]);
    }

    return 0; 
}```


Source: StackOverflow C++

LEAVE A COMMENT