I'm trying to create a code to remove the same elements in arrays. The problem is EXC_BAD_ACCESS (Code = 1, address = 0x30000008) issue. My code is: `
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand (time(NULL));
int i, j, b, c;
double A[11];
double B[10];
char choice;
for (i = 0; i < 11; i++)
{
A[i] = rand () %100;
}
for (j = 0; j < 10; j++)
{
B[j] = rand () % 100;
}
printf("Array A[N]: \n");
for (i = 0; i < 10; i++)
{
printf("%.2lf ", A[i]);
}
printf("\n Array B[M]: \n");
for (j = 0; j < 10; j++)
{
printf("%.2lf ", B[j]);
}
for (i = 0; i < 11; i++)
{
for (j = 0; j < 10; i++)
{
** if (A[i]==B[j])
Exception has occurred.
EXC_BAD_ACCESS (code=1, address=0x16fe00000)**
{
for (c = j; c < 10; c++)
{
B[c] = B[c+1];
}
j--;
}
}
}
printf("\n New array B[M]: \n");
for ( j = 0; j < 9; j++)
{
printf ("%.2lf", B[c]);
}
return 0;
}
` Hope for helping. Thank you
I was trying to define N 11 and M 10, so it would work, but, unfortunately, not.
for (c = j; c < 10; c++){
B[c] = B[c+1];
}
j--;
In this part if c = 9 (last iteration), you have B[9] = B[10]; The size of B is 10, so the maximum value of the index has to be 9.
My solution is the following:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand (time(NULL));
int i, j, b, c;
double A[11];
double B[10];
char choice;
for (i = 0; i < 11; i++)
{
A[i] = rand () %100;
}
for (j = 0; j < 10; j++)
{
B[j] = rand () % 100;
}
printf("Array A[N]: \n");
for (i = 0; i < 10; i++)
{
printf("%.2lf ", A[i]);
}
printf("\n Array B[M]: \n");
for (j = 0; j < 10; j++)
{
printf("%.2lf ", B[j]);
}
int max_j = 10;
for (i = 0; i < 11; i++)
{
for (j = 0; j < max_j; j++)
{
if (A[i]==B[j])
{
for (c = j; c < max_j-1; c++) {
B[c] = B[c+1];
}
B[max_j-1] = 0;
max_j--;
}
}
}
printf("\n New array B[M]: \n");
for ( j = 0; j < 9; j++)
{
printf ("%.2lf ", B[j]);
}
return 0;
}