Emanuele - 1 month ago 8
C Question

# segmentation fault in C comparing integer members from structure to array in main

I get segmentation fault in the line below.

``````if((rel[i].node1 == SI && rel[i].node2 == gates[j]) || (rel[i].node2 == SI && rel[i].node1 == gates[j])
``````

Now, all the variables/members are integers and they are initialized.
I don't really know what to do.
I tryied to change indexes as well.

I hope to get some help, thank you in advance.

Code:

``````#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
struct relationship {
int node1;
int node2;
};

int main()
{

int N; // the total number of nodes in the level, including the gateways
int L; // the number of links
int E; // the number of exit gateways
scanf("%d%d%d", &N, &L, &E);

int gates[E];
struct relationship rel[L];

for (int i = 0; i < L; i++) {
int N1; // N1 and N2 defines a link between these nodes
int N2;
scanf("%d%d", &N1, &N2);
rel[i].node1 = N1;
rel[i].node2 = N2;
}

for (int i = 0; i < E; i++) {
int EI; // the index of a gateway node
scanf("%d", &EI);
gates[i] = EI;
}

while (1) {
int SI; // The index of the node on which the Skynet agent is positioned this turn
scanf("%d", &SI);

int i, j;
for(i=0; i < L; i++){

//for(j=0; j <E; j++){

if((rel[i].node1 == SI && rel[i].node2 == gates[j]) || (rel[i].node2 == SI && rel[i].node1 == gates[j])) {
printf("%d %d ood\n", rel[i].node1, rel[i].node2);
rel[i].node1 = -1;
rel[i].node2 = -1;

}
// }
/*if(SI == rel[i].node1 || SI ==rel[i].node2){
printf("%d %d %d \n", rel[i].node1, rel[i].node2, SI);
//printf("%d %d\n", rel[i].node1, rel[i].node2);
rel[i].node1 = -1;
rel[i].node2 = -1;
break;
}*/
}
}

return 0;
}
``````

You did not initialise j, thus `gates[j]` ends up with a segmentation fault.