Let's see what your code does. First we have this:
no *lista, *cabeca;
In this line above, you declare the lista
and cabeca
pointers, not initialized. Then we have this:
cabeca = malloc(sizeof(no));
cabeca->prox = NULL;
Here, you make cabeca
point to an allocated memory region to save a node and sets the next node to be NULL
, so as not to leave the uninitialized pointer. However, the reference cabeca->valor
remains uninitialized.
Next we have this:
cabeca = lista;
OPS! Here you are putting% of the contents of an uninitialized pointer in%. As the old reference is lost, we also have a memory leak.
Now inside cabeca
, we have this:
lista = malloc(sizeof(no));
lista->valor = n-i;
You are creating a new node and putting it in the for
variable. All right.
Soon after:
lista->prox = cabeca->prox;
Remember that cabeca
was an uninitialized pointer? Well, it means that cabeca
will give a segmentation fault!
Next:
cabeca->prox = lista;
If this were to run, it would be another segmentation flaw.
Finally, this last bit, I think it's 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]);
}