0
I was doing this code whose goal is to use pointers to fill an array with an arithmetic progression. But I can’t get out of the first loop.
int main() {
int r, // Razão da PA
i, // Contadora
pa[10], // Array que será preenchido pela PA
*ptrPA; // Ponteiro que vai apontar para o Array
printf("Digite o primeiro termo da PA: \n");
scanf("%d", &pa[0]);
printf("Digite a razão da PA: \n");
scanf("%d", &r);
for (ptrPA = &pa[0] + 1; ptrPA <= &ptrPA[9]; ptrPA++) { // O ponteiro vai servir como contador
*ptrPA = *(ptrPA - 1) + r; // Aplica-se a fórmula de PA para a posição do endereço que o ponteiro aponta
}
for (i = 0; i < 10; i++) {
printf("%d ", pa[i]); // Exibe os valores armazenados
}
return 0;
}
What could be causing this? Thank you.
PS: When I try to run the program it closes after I enter the values, and in the eclipse debug it gets stuck in the first loop
Is there a reason to use the pointer? It doesn’t seem necessary.
– Maniero
It really isn’t, it’s just for exercise
– Jefferson Carvalho
Normally I can improve this and solve, the problem is that I don’t know if I’m going to take something you artificially put out. When there is an invented requirement, it is difficult to give an answer. I would simply remove the pointer, after all I do not know what to learn
ptrPA = &pa[0] + 1; ptrPA <= &ptrPA[9];
but surely the error is there.– Maniero
I am assigning to the pointer the memory address of position '1' of the array, as position '0' is already being occupied by the first element I had asked the user. The condition for the loop to run is that I have a memory address less than or equal to the last position of the array (in this case it is position 9). The problem must be right there, I don’t know why the loop doesn’t close after the ninth position.
– Jefferson Carvalho
With this code I was trying to answer this exercise: http://www.cprogressivo.net/2013/03/Operacoes-Matematicas-comPonteiros-em-C.html
– Jefferson Carvalho