In this chained list, a vector of 10 positions is set.
First, you must choose which position to complete and then how many values to add (% with%). So far so good.
The problem is that I'm trying to sort the vectors incrementally, but I'm doing something wrong that I still can not identify.
This same code with unique vectors and / or pointers works. With the struct, something is wrong.
My code:
#include <stdio.h>
#include <stdlib.h>
#define TAM 10
//Seto o struct
struct listaDados {
int *vetPont;
int *vetOrdenado;
int qtd;
int escolha;
} lista[TAM];
//Seto as funções
void listarDadosOrdenados(struct listaDados *lista);
int insereDados(struct listaDados *lista);
Enter data:
int insereDados(struct listaDados *lista){
int i, j, aux;
printf("De 1 a 10, qual vetor voce deseja escolher?");
scanf("%d", &aux);
aux -= 1;
lista[aux].escolha = aux;
if(lista[aux].vetPont > 0){
printf("Estrutura já preenchida");
return 0;
} else {
printf("Digite a qtd de elementos que voce deseja inserir:");
scanf("%d", &lista[aux].qtd);
lista[aux].vetPont = (int *) malloc(lista[aux].qtd * sizeof(int));
printf("Agora, insira %d numeros no vetor %d\n", lista[aux].qtd, (lista[aux].escolha+1));
for(i=0; i<lista[aux].qtd; i++){
scanf("%d", &lista[aux].vetPont[i]);
}
}
}
List Ordered Data:
void listarDadosOrdenados(struct listaDados *lista){
int i, j, aux;
for(i=0; i<TAM; i++){
lista[i].vetOrdenado = (int *) malloc(lista[i].qtd * sizeof(int));
for(j=0; j<lista[i].qtd; j++){
lista[i].vetOrdenado[j] = lista[i].vetPont[j];
}
}
for(i=0; i<TAM; i++){
for(j=i+1; j<lista[i].qtd; j++){
if( lista[i].vetOrdenado[i] > lista[i].vetOrdenado[j]){
aux = lista[i].vetOrdenado[i];
lista[i].vetOrdenado[i] = lista[i].vetOrdenado[j];
lista[i].vetOrdenado[j] = aux;
}
}
}
for(i=0; i<TAM; i++){
printf("Posicao: %d\n", i+1);
if(lista[i].qtd > 0){
printf("Itens: %d\n", lista[i].qtd);
printf("Valores: ");
for(j=0; j<lista[i].qtd; j++){
printf("%d", lista[i].vetOrdenado[j]);
if(j < (lista[i].qtd-1)){
printf(" - ");
}
}
} else {
printf("Itens: 0\nValores: 0");
}
puts("\n\n");
}
}
In malloc
function, first I allocate the same amount of memory from listarDadosOrdenados
to *vetPont
, I did this because I do not want to overwrite *vetOrdenado
. I also printed the values of *vetPont
and the values are being transferred normally, the problem is sorting.
The exchange algorithm is this , I did it without the struct and it worked.
The problem is that the sorting algorithm is not working, so I understand it comes in only once and then no more.
Where am I going wrong? Can anyone help me?