Let’s see what your code does. First we have this:
no *lista, *cabeca;
On this line above, you declare the pointers lista
and cabeca
, not initialized. Then we have this:
cabeca = malloc(sizeof(no));
cabeca->prox = NULL;
Here, you do it cabeca
point to an allocated memory region to store a node and set the next node to be NULL
, not to leave the pointer initialized. However, the reference cabeca->valor
still not initialized.
Next we have it:
cabeca = lista;
OPS! Here you are putting in cabeca
the contents of an uninitialized pointer. As the old reference is lost, we also have a memory leak.
Already inside the for
, we have it:
lista = malloc(sizeof(no));
lista->valor = n-i;
Is creating a new node and putting in the variable cabeca
. All right yet.
Right after:
lista->prox = cabeca->prox;
Do you remember that cabeca
was an uninitialized pointer? Yeah, that means cabeca->prox
will give a segmentation failure!
Next:
cabeca->prox = lista;
If it were to perform, it would be another segmentation failure.
Finally, this last part, I think is correct:
scanf("%d", &r1);
r2 = malloc(r1*sizeof(int));
for(j = 0; j < r1; j++){
scanf("%d ", &r2[j]);
}
I think what you wanted was this:
no *lista = NULL, *cabeca = NULL;
int i, j, n, r1, *r2;
scanf("%d", &n);
for (i = 0; i < n; i++) {
lista = malloc(sizeof(no));
lista->valor = n - i;
lista->prox = cabeca;
cabeca = lista;
}
scanf("%d", &r1);
r2 = malloc(r1 * sizeof(int));
for (j = 0; j < r1; j++) {
scanf("%d ", &r2[j]);
}
edit your question by formatting the code...in the edit window menu has a key open/close icon...select the lines of code with the mouse and click the key open/close icon, otherwise your code becomes unreadable
– zentrunix