Exception thrown

I got a code like this, in order to print out the max element, position of a number, and prime elements in an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
int findMax(int a[], int n, int max)
{
	if (n == 0)
	{
		return max;
	}
	else
	{
		if (a[n] > max)
		{
			max = a[n];
		}
		return findMax(a, n - 1, max);
	}
}
int FindX(int a[], int l, int r, int x)
{
	if (r < l)
	{
		return -1;
	}
	if (a[l] == x)
	{
		return l;
	}
	if (a[r] == x)
	{
		return r;
	}
	return FindX(a, l + 1, r - 1, x);
}
int Prime(int x, int i)
{
	if (i == 1)
	{
		return 1;
	}
	else
	{
		if (x % i == 0)
		{
			return 0;
		}
		else
		{
			return Prime(x, i - 1);
		}
	}
}
void OutputPrime(int a[], int n)
{
	for (int i = 0; i < n; i++)
	{
		if (Prime(a[i], a[i] / 2) == 1)
		{
			printf("%d", a[i]);
			printf("\n");
		}
	}
}

int main()
{
	int a[100], n, sum = 0, x;
	printf("Enter the number of elements: ");
	scanf("%d", &n);
	printf("Enter the elements:\n");
	for (int i = 0; i < n; i++)
	{
		scanf("%d", &a[i]);
	}
	int max = a[0];
	max = findMax(a, n - 1, max);
	printf("The largest number in the array is: %d", max);
	printf("Enter x: ");
	scanf("%d", &x);
	printf("The position of x in the array is: %d", FindX(a, 0, n - 1, x));
	printf("Prime numbers in the array: ");
	OutputPrime(a, n);
	return 0;
}

The compiler told me that: at the line 26: Exception thrown: read access violation. **a** was 0x34D22E36.
What does it mean? And how to get it fixed?
Last edited on
instead of scanf for int n, try fgets.
fgets??
fgets ( char * str, int num, FILE * stream );
I thought using it only for working with files.
How to use fgets in this situation?
On line 67. It's just a trial and error thing though. Don't take it to the bank.
You mean:
fgets(n, 100, stdin);
Right?
How about initializing max = a[0]; inside the function, delete the max parameter
Topic archived. No new replies allowed.