当我编译我的代码时并没有给我任何错误,但是当我运行它时,出现以下错误:
结果应改为:
我的代码应该通过从0到9的随机数字数组中返回数字的位置来“加密”一个数字。
这是我的代码:
#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;
}
问题是为什么出现分割错误是因为您的输入处理不正确,因为scanf
也将尝试转换空白。因此,您给数字5赋值,然后按Enter键,实际上是在Linux上写了\n
,在Windows上写了\r\n
。因此,在Linux上,根据操作系统的不同,数组a
的前端将具有一个或两个无效值。最简单的解决方法是将代码替换为