0
I’m not getting why of this error, Segmentation fault. Segment error, apparently.
I have a code in which the user sends values that are recorded in an array. This array has two dimensions, the 2D will have two houses, one where the item number will be stored and the other the number of units, each item in the 1D of the array will be a request. There are 7 items, so the loop breaks if the user gives a value that is not between 1-7. Every p loop of orders is added +1. Here I left the code simplified, just to highlight the logic to be analyzed:
int main()
{
int cont;
int p = 0;
int compra[][2] = {{0,0}};
for (cont=0; cont <= 7; cont=0) {
printf("\n\nPedido %d\n", (p+1));
printf("\nQual item você quer?\n%sItem ");
scanf("%d", &cont);
if(cont > 7 || cont < 1) break;
compra[p][0] = cont;
printf("\n\nQuantas unidades?\nUnidade(s): ");
scanf("%d", &compra[p][1]);
p++;
}
char produto[][100] = {
"cachorro(s)-quente",
"X-salada(s)",
"X-bacon(s)",
"misto(s)",
"prato(s) de salada",
"garrafa(s) de água",
"refrigerante(s)"
};
Soon after all values are sent I want to show the values like this:
for (cont = 0; cont <= p-1; cont++) {
int item = compra[cont][0];
printf("\n %d %s;\n",
compra[cont][1], produto[(item-1)]);
}
}
I tried to use a loop, it prints the first item but gives segment error and does not print the rest.
And then I dropped the loop and tried so to see:
printf("\n%s %d %s;\n", margem,
compra[0][1], produto[(compra[0][0]-1)]);
printf("\n%s %d %s;\n", margem,
compra[1][1], produto[(compra[1][0]-1)]);
printf("\n%s %d %s;\n", margem,
compra[2][1], produto[(compra[2][0]-1)]);
printf("\n%s %d %s;\n", margem,
compra[3][1], produto[(compra[3][0]-1)]);
Same thing. I took the part where the user sends the values and left the items of the purchase array ready, so:
int main()
{
int p = 4;
int cont;
int compra[][2] = {{3,4},{1,7},{7,2},{2,1}};
char produto[][100] = {
"cachorro(s)-quente",
"X-salada(s)",
"X-bacon(s)",
"misto(s)",
"prato(s) de salada",
"garrafa(s) de água",
"refrigerante(s)"
};
for (cont = 0; cont <= p-1; cont++) {
int item = compra[cont][0];
printf("\n %d %s;\n",
compra[cont][1], produto[(item-1)]);
}
}
And it works, so probably the error that is causing the Segmentation Fault is in that stretch that I took, I suspect that the loop is not sending values only modifying what has already been filled, but why?
Edit:
What’s more, when I do the same thing as above, however, adding a scanf to send one more item to the array gives the same error, even without the loop.
The problem lies in this scanf?
How many purchases you want to store at most?
– chriptus13
It is undefined. It is not possible to leave indefinite?
– Felipe Alves