Here's the following problem, Im getting Asisgnment from incompatible pointer types in the next code:
TO resume this to you the line 43 goes as follows:
aux->sig=nodo;
Line 60 :
aux2=aux2->sig;
Basically im getting every error in "aux2"
Whats is causing this? And if you could explain this to me, Im a student and Im basically new to programming.
proyecto2mod.c: In function ‘agrega_nombre’:
proyecto2mod.c:43: warning: assignment from incompatible pointer type
proyecto2mod.c:60: warning: assignment from incompatible pointer type
proyecto2mod.c: In function ‘busca_cliente’:
proyecto2mod.c:105: warning: assignment from incompatible pointer type
proyecto2mod.c: In function ‘ordena’:
proyecto2mod.c:118: warning: assignment from incompatible pointer type
proyecto2mod.c:119: error: request for member ‘nombre’ in something not a structure or union
proyecto2mod.c:119: error: request for member ‘nombre’ in something not a structure or union
proyecto2mod.c:120: error: request for member ‘direccion’ in something not a structure or union
proyecto2mod.c:120: error: request for member ‘direccion’ in something not a structure or union
proyecto2mod.c:121: error: request for member ‘num_cliente’ in something not a structure or union
proyecto2mod.c:122: error: request for member ‘ant’ in something not a structure or union
...
And So on.
Heres the Codes:
MAIN CODE
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "clientes.h"
#include "ventas.h"
extern void agrega_nombre(ApLista1 inicio, ApLista1 aux,ApLista1 nodo, ApLista1 aux2);
extern void busca_cliente(ApLista1 inicio, ApLista1 aux,ApLista1 nodo, ApLista1 aux2, ApLista2 inicioventas, ApLista2 auxventas, ApLista2 nodoventas, ApLista2 aux2ventas);
extern int ordena(ApLista1 inicio, ApLista1 aux,ApLista1 nodo,ApLista1 *aux2);
int main(void)
{
int menu=0;
//LISTA1 *aux2,*nodo;
ApLista1 inicio, aux, nodo, aux2;
ApLista2 inicioventas, auxventas,nodoventas,aux2ventas;
inicio=NULL;
nodo=malloc(sizeof(LISTA1));
aux=malloc(sizeof(LISTA1));
inicioventas=NULL;
nodoventas=malloc(sizeof(LISTA2));
auxventas=malloc(sizeof(LISTA2));
system("clear");
while(menu!='6')
{
//funcion void carga_datos();
printf("TIENDA DEPARTAMENTAL\n\n\n");
printf("1. Agregar a un Cliente.\n2. Agregar una venta.\n3. Buscar Cliente. \n4. Borrar Cliente. \n5. Borrar una venta. \n6. Salir.");
printf("\n\nElige una opcion: ");
scanf("%d", &menu);
switch(menu)
{
case 1:
system("clear");
printf("opcion1\n");
agrega_nombre(inicio, aux,nodo, aux2);
menu=0;
break;
case 2:
system("clear");
printf("opcion2\n");
///lo mismo que agrega_cliente pero utilizando la lista de ventas.
menu=0;
break;
case 3:
system("clear");
printf("opcion3\n");
busca_cliente(inicio,aux,nodo,aux2,inicioventas, auxventas, nodoventas, aux2ventas);
menu=0;
break;
case 4:
system("clear");
printf("opcion4\n");
//borra_cliente(inicio,aux,nodo,aux2,inicioventas, auxventas, nodoventas, aux2ventas);
menu=0;
break;//
case 5:
system("clear");
printf("opcion5\n");
//Lo Mismo que borra cliente pero en la lista de ventas solamente.
menu=0;
break;
case 6:
system("clear");
printf("Adios!\n");
exit(1);
menu=0;
break;
}
}
}
Functions that go in main:
void agrega_nombre(ApLista1 *inicio, ApLista1 aux,ApLista1 nodo, ApLista1 aux2)
{
FILE *clientes;
int pops=0, sanders=0;
char aux_char[80];
system("clear");
clientes=fopen("clientes.txt", "a+");
//fseek(clientes, 0L, SEEK_END);
if(nodo==NULL)
{
printf("No hay memoria\n");
exit(1);
}
printf("NOMBRE:");
scanf("%s", nodo->nombre);
printf("DIRECCION:");
scanf("%s",nodo->direccion);
printf("NUMERO DE CLIENTE:");
scanf("%d", &nodo->num_cliente);
if(inicio==NULL)
{
(*inicio)=nodo;
(*inicio)->sig=NULL;
(*inicio)->ant=NULL;
aux=(*inicio);
}
else
{
aux->sig=nodo;
nodo->ant=aux;
aux=nodo;
nodo->sig=NULL;
}
pops++;
aux2=(*inicio);
while(aux2!=NULL)
{
fprintf(clientes, "%s\n", aux2->nombre);
fprintf(clientes, "%s\n", aux2->direccion);
fprintf(clientes, "%d\n", aux2->num_cliente);
puts(aux2->nombre);
puts(aux2->direccion);
aux2=aux2->sig;
}
aux2=aux;
do
{
puts(aux2->nombre);
aux2=aux2->ant;
}
while(aux2!=NULL);
fclose(clientes);
}
//Funcion Busqueda
void busca_cliente(ApLista1 inicio, ApLista1 aux,ApLista1 nodo, ApLista1 aux2, ApLista2 inicioventas, ApLista2 auxventas, ApLista2 nodoventas, ApLista2 aux2ventas)
{
char nombrebusqueda[80];
int numclienteprueba;
inicio=NULL;
printf("Dame el nombre del cliente a buscar\n");
scanf("%s",nombrebusqueda);
aux2=aux;
while(aux2!=NULL)
{
printf("Entramos al While Aux2");
if((strcmp(nombrebusqueda,aux2->nombre))==0)
{
printf("Encontramos BAM");
puts(aux2->nombre);
////////Buscamos la venta
aux2ventas=auxventas;
while(aux2ventas!=NULL)
{
numclienteprueba=aux2ventas->num_clienteventas;
if(numclienteprueba==aux2ventas->num_clienteventas)
{
printf("Wow");
///Aqui ensenamos las ventas que ha tenido el cliente y la i informacion de la estructura.
}
aux2ventas=aux2ventas->sigvent;
}
////////////
}
aux2=aux2->sig;
}
}
//Funcion Ordena
int ordena(ApLista1 inicio, ApLista1 aux,ApLista1 nodo,ApLista1 *aux2)
{
char pruebaman[80],probaman[80];//nombres
char pruebadireccion[150],probadireccion[150];//direccion
int pruebanum_cliente,probanum_cliente;//numero de cliente
aux2=aux;
strcpy(pruebaman,aux2->nombre);
strcpy(pruebadireccion,aux2->direccion);
pruebanum_cliente=aux2->num_cliente;
aux2=aux2->ant;
do
{
strcpy(probaman,aux2->nombre);
if(pruebaman[0]<probaman[0])
{
strcpy(pruebaman,aux2->nombre);
strcpy(pruebadireccion,aux2->direccion);
pruebanum_cliente=aux2->num_cliente;
aux2=aux2->sig;
strcpy(aux2->nombre,probaman);
strcpy(aux2->direccion,probadireccion);
probanum_cliente=aux2->num_cliente;
}
strcpy(pruebaman,aux2->nombre);
strcpy(pruebadireccion,aux2->direccion);
pruebanum_cliente=aux2->num_cliente;
aux2=aux2->ant;
printf("Ciclo\n\n");
}
while(aux2!=NULL);
aux2=aux;
strcpy(pruebaman,aux2->nombre);
aux2=aux2->ant;
strcpy(probaman,aux2->nombre);
if(pruebaman[0]<probaman[0])
ordena(inicio,aux,nodo,aux2);
}
Structures:
#include<stdio.h>
typedef struct clientes{
char nombre[80];
char direccion[150];
int num_cliente;
struct cliente*sig;
struct clientes *ant;
struct ventas *vent;
}LISTA1;
typedef struct clientes *ApLista1;
Second Structure:
#include<stdio.h>
typedef struct ventas{
int num_clienteventas;
char nombre_producto[150];
int precio;
int unidades;
char fecha[11];
struct ventas *sigvent;
struct ventas *antvent;
}LISTA2;
typedef struct ventas *ApLista2;
In int ordena(), you define aux2 as an ApLista1*, which is basically a struct clientes**. You then try to assign it into aux, which is defined as ApLista1 aux, namely a struct clientes* - note the missing star.
aux2 being a pointer to a pointer to a struct, it's clear why calls like aux2->nombre are not compiling. The solution is to either define aux2 as ApLista1, or dereference it when needed.
Oh, and as a side note - IMO, hiding *s behind typedefs is not a good practice. It doesn't help you type less, and it makes the code less readable - and as in this case, more error prone.
Related
good morning, I am making a calculator with a "Stack" of 10 positions in the "C" lenguage. What I have to do is, for example, I write the number "50", I press ENTER and that "50" must go to the first position "01". Then I write another number, for example "20" + ENTER and 20 should go to position "01", "50" goes up to "02" and so on, always after pressing ENTER. I am using the Gotoxy for this.
I can manage to print the first number in position "01" but after that I don't know how to proceed.
I'm new to programming so excuse me if I don't realize obvious things, I'm trying to learn so if you can give me a hand I would appreciate it. Here I leave the code in case you want to try it and get an idea of what I'm trying to do, thanks
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
void gotoxy(int x, int y);
void PilaPush();
void ImprimirPila();
int main() {
printf(" ____________________________________________________\n");
printf("|10:_________________________________________________|\r\n");
printf("|09:_________________________________________________|\r\n");
printf("|08:_________________________________________________|\r\n");
printf("|07:_________________________________________________|\r\n");
printf("|06:_________________________________________________|\r\n");
printf("|05:_________________________________________________|\r\n");
printf("|04:_________________________________________________|\r\n");
printf("|03:_________________________________________________|\r\n");
printf("|02:_________________________________________________|\r\n");
printf("|01:_________________________________________________|\r\n");
printf("| |\r\n");
printf("| |\r\n");
printf("|____________________________________________________|\r\n");
printf("|_____1_____|_____2_____|_____3_____|__+__|__DROP[P]_|\r\n");
printf("|_____4_____|_____5_____|_____6_____|__-__|__SWAP[S]_|\r\n");
printf("|_____7_____|_____8_____|_____9_____|__*__|__DEL[D]__|\r\n");
printf("|_____,_____|_____0_____|____EXE____|__/__|__NUM[N]__|\r\n");
printf("|_____'_____|_ARRIBA[W]_|__ABAJO[Z]_|_____|_SWAP1[Q]_|\r\n");
gotoxy(3, 12);
PilaPush();
ImprimirPila();
getch();
return 0;
}
void gotoxy(int x, int y) {
HANDLE Ventana;
Ventana = GetStdHandle(STD_OUTPUT_HANDLE);
COORD Coordenadas;
Coordenadas.X = x;
Coordenadas.Y = y;
SetConsoleCursorPosition(Ventana, Coordenadas);
}
typedef struct Nodo {
int elemento;
struct Nodo *siguiente;
} Nodo;
// funciones para utilizar un manejador global
Nodo *primero = NULL;
// Insertar un nuevo nodo a la pila
void PilaPush() {
Nodo *nuevo;
// crear el nuevo Nodo.
nuevo = (Nodo *)malloc(sizeof(Nodo)); // Asignar de forma dinamica un espacio de memoria al Nodo
printf(" ");
scanf("%d", &nuevo->elemento);
// Agregar el nodo al principio de la Pila
nuevo->siguiente = primero; // El nuevo dato ahora es primero, que apunta a (NULL)
primero = nuevo; // Primero (NULL) ahora es el nuevo dato
}
// sacar un elemento de una pila
void ImprimirPila() {
Nodo *actual = (Nodo *)malloc(sizeof(Nodo));
actual = primero;
if (primero != NULL) {
while (actual != NULL) {
gotoxy(9, 10);
printf("%d", actual->elemento);
actual = actual->siguiente;
gotoxy(3, 12);
printf(" ");
gotoxy(3, 12);
}
} else {
printf("No hay ningun dato ");
}
}
This code tries to implement a doubly linked circular list
The code compiles, does not throw error, but when entering a number is hung where is the fault? Pretend that the signs in Spanish are in English
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <stdlib.h>
struct lista
{
int info;
struct lista *sig,*ant;
}*CAB=NULL,*AUX=NULL,*Q=NULL,*P=NULL,*F=NULL,*QD=NULL,*FD=NULL;
main menu
int main() {
void insertard(void);
void extraerd(void);
void visualizard(void);
void visualizari(void);
void eliminardespues();
void eliminarantes();
char opc;
do{
system("cls");
printf("___________________________________________________\n");
printf("_¡¡¡MENU DE LISTA CIRCULAR DOBLEMENTE ENLAZADA!!!__\n");
printf("___________________________________________________\n");
printf("____________SELECCIONE UNA OPCION__________________\n");
printf("___________________________________________________\n");
printf("___________________________________________________\n");
printf("__________1) INSERTAR______________________________\n");
printf("__________2) VISUALIZAR ASCENDIENTE________________\n");
printf("__________3) VISUALIZAR DESCENDIENTE_______________\n");
printf("__________4) INGRESAR Y ELIMINAR SIGUIENTE_________\n");
printf("__________5) INGRESAR Y ELIMINAR ANTERIOR__________\n");
printf("__________6) SALIR_________________________________\n");
printf("___________________________________________________\n");
opc=getch();
switch(opc)
{
case '1':
insertard();
break;
case '2':
visualizard();
break;
case '3':
visualizari();
break;
case '4':
eliminarantes();
break;
}
} while(opc!='6');
getch();
return 0;
}
Process insertard
void insertard(void)
{
P=CAB;
AUX=(struct lista *)malloc(sizeof(struct lista));
system("cls");
printf("INGRESE UN NUMERO ENTERO:");
scanf("%d",&AUX->info);
AUX->sig=CAB;
AUX->ant=CAB;
F=AUX;
if(CAB==NULL)
CAB=AUX;
}else{ //ESTO SI
while (P->sig!=CAB){
P=P->sig;
}
P->sig=AUX;
AUX->ant=P;
AUX->sig=CAB;
}
eliminardespues Process (Deletes an item after the list)
void eliminardespues(){
int x;
system("cls");
printf("INGRESE UN NUMERO PARA ELIMINAR EL SIGUIENTE:");
scanf("%d",&x);
FD=CAB;
QD=CAB;
while(FD->info!=x&&FD->sig!=CAB){
FD=FD->sig;
}QD=FD->sig;
if(FD->sig==CAB&&FD->info!=x){
printf("\nEL NUMERO INGRESADO NO SE ENCUENTA EN LA LISTA");
}else{
if(FD->info==x){
FD->sig=QD->sig;
(QD->sig)->ant=FD;
printf("\nELIMINADO %d",QD->info);
free(Q);
}
}
getch();
}
Process eliminarantes
void eliminarantes()
{
int x;
system("cls");
printf("INGRESE UN NUMERO PARA ELIMINAR EL ANTERIOR");
scanf("%d",&x);
FD=CAB;
QD=CAB;
while (FD->info!=x&&FD->sig!=CAB){
FD=FD->sig;
}QD=FD->ant;
if(FD->sig==CAB&&FD->info!=x){
printf("\nEL NUMERO INGRESADO NO SE ENCUENTA EN LA LISTA");
}else{
if(FD->info==x){
FD->ant=QD->ant;
(QD->ant)->sig=FD;
printf("\nELIMINADO %d",QD->info);
free(Q);
}
}
getch();
}
void visualizard(void)
{
system("cls");
if(CAB==NULL){
printf("LISTA VACIA");
getchar();
return;
}
AUX=CAB;
printf("LISTA:\n\n");
while(AUX->sig!=CAB){
printf("-> %d\n",AUX->info);
AUX=AUX->sig;
}
if(AUX->sig==CAB){
printf("-> %d\n",AUX->info);
}
getch();
}
void visualizari(void){
system("cls");
if(F==NULL){
printf("LISTA VACIA");
getchar();
return;
}
AUX=F;
printf("LISTA:\n\n");
do{
printf("-> %d\n",AUX->info);
AUX=AUX->ant;
}while(AUX->sig!=CAB);
getch();
}
In your first execution of method 'insertard' you are actually assigning P=CAB; i.e. P=NULL and in the blow line of code you are referring a null pointer to assign value.
P->sig=AUX;
I have modified your method which might fix it.
void insertard(void)
{
P=CAB;/* very first execution of this method P=NULL */
AUX=(struct lista *)malloc(sizeof(struct lista));
system("cls");
printf("INGRESE UN NUMERO ENTERO:");
scanf("%d",&AUX->info);
AUX->sig=CAB;
AUX->ant=CAB;
F=AUX;
if(CAB==NULL){
CAB=AUX;
P = AUX;/*first execution of this method P is no longer NULL but P is pointing to AUX */
}else{ //ESTO SI
while (P->sig!=CAB){
P=P->sig;
}
P->sig=AUX;
AUX->ant=P;
AUX->sig=CAB;
}
#include<stdio.h>
#include"push.c"
#include"pop.c"
#include"listadopila.c"
#include"structpila.c"
int main ()
{
struct pila valor;
void push();
int pop();
void listado();
int opcion=0;
valor.tope= -1;
int continuar;
printf ("=====ESTRUCTURA DE PILA=====\n\n");
do
{
printf ("Ingresa tu opcion:\n");
printf ("1) Para push\n");
printf ("2) Para pop\n");
printf ("3) Para mostrar tu pila\n");
printf ("4) Para salir.\n");
printf ("\n");
printf ("Ingresa tu opci%cn\n",163);
scanf("%d", &opcion);
switch(opcion)
{
case 1:
push(valor);
break;
case 2:
pop(valor);
break;
case 3:
listado(valor);
break;
default:
printf("Opción no válida.\n");
}
printf("\n¿Desea continuar comprando? Pulse cualquier tecla para si y N para no: ");
getchar();
scanf("%d",&continuar);
continuar=getchar();
}
while(continuar!='n'&&continuar!='N');
}
In other file, I define the struct like this:
struct pila
{
int pila[5];
int tope;
}valor;
And my functions are like this:
int pop()
{
int numero;
if (valor.tope==- 1)
{
printf ("La pila esta vacia.\n");
return (valor.tope);
}
else
{
numero=valor.pila[valor.tope];
printf("El elemento que haz eliminado es= %d", valor.pila[valor.tope]);
valor.tope=valor.tope -1;
}
return(numero);
}
I've tried changing the struct inside and outside the main and to write the functions into the switch case like: pop(valor); but it doesn't work either. Also in the files of each function I've tried to write the function like "int pop(struct pila valor)" but the compiler says I need to add a lenght for valor, the problem is that when I did the code in the same file the compilation finished succesfully, so the problem is when I try to link the struct with the other functions.
Any help?
I have this code and I don't know why after, I ask if you want to introduce another student and I say 1 or 0 the program ends and said segmentation fault (core dumped).
I ask to introduce another student in _nodo *insertaEnLista
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct actividades
{
char tipoDeActividad[22];
char diaDeLaSemana[12];
char horaDeIncio[8];
char horaDeFin[8];
};
struct materias
{
char nombre[30];
char profesor[30];
char tipoDeMateria[20];
struct actividades *actividad;
};
struct alumnos
{
char nombre[30];
int cedula;
int telefono;
struct materias *materia;
struct alumnos *siguiente;
};
typedef struct alumnos _nodo;
_nodo *crearLista(_nodo *apuntador);
bool listaVacia(_nodo *apuntador);
_nodo *insetarEnLista(char nombre[], long cedula, long telefono, _nodo *apuntador);
void imprimirLista (_nodo *apuntador);
_nodo *crearNodo(char nombre[], long int cedula, long int telefono);
//AQUI SE CREA LISTA Y SE PONE PARA QUE APUNTE A NULL
_nodo *crearLista(_nodo *apuntador)
{
return (apuntador = NULL);
}
//ESTA FUNCION VERIFICA SI LA LISTA ESTA VACIA
bool listaVacia(_nodo *apuntador)
{
if (apuntador == NULL)
return (true);
else
return (false);
}
//AQUI SE CREA EL NUEVO NODO DE LA LISTA
_nodo *crearNodo(char nombre[], long cedula, long telefono)
{
_nodo *registroNuevo;
registroNuevo = (_nodo *) malloc(sizeof(_nodo));
printf("\n----NUEVO ELEMENTO----\n");
printf("NOMBRE: ");
fflush(stdin);
scanf("%s",nombre);
printf("CEDULA: ");
fflush(stdin);
scanf("%ld", &cedula);
printf("TELEFONO: ");
fflush(stdin);
scanf("%ld", &telefono);
fflush(stdin);
strcpy(registroNuevo->nombre, nombre);
registroNuevo->cedula = cedula;
registroNuevo->telefono = telefono;
registroNuevo->siguiente = NULL;
return registroNuevo;
}
//AQUI SE INSERTA EL NODO EN LA LISTA LUGEO DE SER CREADO POR LA FUNCION crearNodo
_nodo *insetarEnLista(char nombre[], long cedula, long telefono, _nodo *apuntador)
{
_nodo *registroNuevo, *apuntadorAuxiliar;
char respuesta,ch;
do
{
registroNuevo=crearNodo(nombre, cedula, telefono);
if (listaVacia(apuntador)) apuntador = registroNuevo;
else
{
apuntadorAuxiliar = apuntador;
while (apuntadorAuxiliar->siguiente != NULL)
apuntadorAuxiliar = apuntadorAuxiliar->siguiente;
apuntadorAuxiliar->siguiente = registroNuevo;
}
printf("\nPARA INGRESAR A OTRO ALUMNO MARQUE... 1");
printf("\nPARA SALIR MARQUE... '0'\n");
while((ch = getchar()) != EOF && ch != '\n');
scanf("%c", &respuesta);
fflush(stdin);
printf("RESPUESTA = %c", respuesta);
}while (strcmp(&respuesta, "1")==0);
return apuntador;
}
//IMPRIMIR LOS NODOS DE LA LISTA
void imprimirLista (_nodo *apuntador)
{
_nodo *apuntadorAuxiliar;
apuntadorAuxiliar = apuntador;
if (apuntador == NULL)
printf("NO HAY ELEMENTOS EN LA LISTA \n");
else
{
while(apuntador != NULL)
{
printf(" \n------------NODO-------------- ");
printf("\nNOMBRE: %s \n\n", apuntadorAuxiliar->nombre);
printf("\n\nCEDULA: %d \n", apuntadorAuxiliar->cedula);
printf("\nTELEFONO: %d \n", apuntadorAuxiliar->telefono);
apuntadorAuxiliar = apuntadorAuxiliar->siguiente;
}
}
return;
}
int main()
{
/*printf("INTRODUZCA LOS NUMEROS DE CEDULA QUE DESEA IMPRIMIR \n");*/
_nodo *inicioLista;
int cedula;
int telefono;
char nombre[20];
inicioLista = crearLista(inicioLista);
inicioLista = insetarEnLista(nombre, cedula, telefono, inicioLista);
imprimirLista(inicioLista);
return 0;
}
How can I do to fix the problem.
You should step through the code in a debugger and look at the variables at each step to determine the line of code that is causing the issue.
Here is one issue, there may be others.
In this line
}while (strcmp(&respuesta, "1")==0);
you are using strcmp with a variable (respuesta) that contains a single character. strcmp is expecting a null terminated string (an array of characters with a zero byte at the end). As you may not have a zero byte after the variable, this may cause strcmp to read memory that it shouldn't (this is a buffer overrun)
Much simpler to just use:
}while (respuesta == '1');
This is a program to register books in a library with title, writer and price.As well as calculate things such as averages, highest price book... It ran pretty well when i used a vector {struct livro Livros[1000]} instead of a pointer {struct livro *Livros}.
I used the pointers to dynamically allocate memory for the book list and everything runs fine registering the books. but when i try to calculate the average, which calls another function to main, the program crashes and the compiler(i use visual studio in my school) shows that message:
Unhandled exception at 0x00ec174c in Livraria.exe: 0xC0000005: Access violation reading location 0xcccccd94.
I tried to use the function to locate by writer instead of the average and it crashed just after i have put the string. Certainly when it used the "Livros[i].autor" to compare the strings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define flush_toilet (fflush(stdin))
//mude o #define dependendo do seu SO
//__fpurge(stdin); "linux"
//fflush(stdin); "windows"
struct livro {
char titulo [100];
char autor [100];
float prec;
};
//register
void cadastro (int *qtd, struct livro *Livros){
int i;
Livros=NULL;
printf("Insira a quantidade de livros:");//defines the quantity(variable "qtd") of books which will pass to the main function(it worked when i used vectors)
scanf ("%i",qtd);
flush_toilet;
Livros = malloc( *qtd *sizeof(struct livro)); //allocates the memory for the list
printf ("insira os dados de cada livro:");
for (i=0;i<*qtd;i=i+1){
printf ("\n\n\ninsira o titulo:");
gets (Livros[i].titulo); //title
flush_toilet;
printf ("\ninsira o nome:");
gets (Livros[i].autor); //writer
flush_toilet;
printf ("\ninsira o preco :");
scanf ("%f",&Livros[i].prec);//price
flush_toilet;
}
}
//calculate average of prices
float media (int qtd, struct livro *Livros){
int i;
float media=0;
for (i=0;i<qtd;i=i+1){
media=media+Livros[i].prec;
}
media=media/qtd;
return media;
}
//calculate number of books above average
int qtd_acima_med (float media, struct livro *Livros, int qtd){
int acima=0,i;
for (i=0;i<qtd;i=i+1){
if(Livros[i].prec>media){
acima=acima+1;
}
}
return acima;
}
//locate a book by writer
void localizar(int qtd, struct livro *Livros){
int i;
char autor[100];
printf("\ndigite o nome do autor cujos livros deseja encontrar:\n");
gets (autor);
flush_toilet;
printf("\n");
for (i=0;i<qtd;i=i+1){
if((strcmp (autor, Livros[i].autor))==0){
puts(Livros[i].titulo);
printf("\n");
}
}
}
//finds and displays the most expensive book
void mais_caro (int qtd, struct livro *Livros ){
int i, ncaro;
float caro=0;
for (i=0;i<qtd;i=i+1){
if (Livros [i].prec>caro){
caro=Livros [i].prec;
ncaro=i;
}
}
puts (Livros[ncaro].titulo);
printf ("preco: %f\n", Livros[ncaro].prec);
}
void main (){
struct livro *Livros;
int qtd=-1, selec=1, nacima=-1;
float med=-1;
while (selec!=0){
printf ("\n\n\nDigite 0 para sair,\n 1 para cadastrar,\n 2 para calcular a media,\n 3 para calcular os livros acima da media,\n 4 para localizar o livro pelo autor,\n 5 para achar o mais caro.\n\n");
scanf("%i", &selec);
flush_toilet;
switch (selec){
case 0:
break;
case 1:{
cadastro(&qtd, Livros);
break;
}
case 2:{
if(qtd<0){
printf("erro nenhum livro cadastrado ou processo de cadastro incorreto\n");
break;
}
med=media(qtd, Livros);
printf("A media e igual a: %f \n", med);
break;
}
case 3:{
if(med<0){
printf("erro a media n foi calculada\n");
break;
}
nacima = qtd_acima_med (med, Livros, qtd);
printf("A qtd de livros com preco acima da media e: %i \n", nacima);
break;
}
case 4:{
if(qtd<0){
printf("erro nenhum livro cadastrado ou processo de cadastro incorreto\n");
break;
}
localizar(qtd, Livros);
break;
}
case 5:{
if(qtd<0){
printf("erro nenhum livro cadastrado ou processo de cadastro incorreto\n");
break;
}
mais_caro (qtd, Livros);
break;
}
}
}
free(Livros);
}
When I compile, I get the following error:
1>main.c(138) : warning C4700: uninitialized local variable 'Livros' used
This looks to be the cause of the bug. To fix, you need to return the allocated array from cadastro:
struct livro * cadastro (int *qtd){
int i;
struct livro *Livros =NULL;
printf("Insira a quantidade de livros:");//defines the quantity(variable "qtd") of books which will pass to the main function(it worked when i used vectors)
scanf ("%i",qtd);
flush_toilet;
Livros = malloc( *qtd * sizeof(struct livro)); //allocates the memory for the list
printf ("insira os dados de cada livro:");
for (i=0;i<*qtd;i=i+1){
printf ("\n\n\ninsira o titulo:");
gets (Livros[i].titulo); //title
flush_toilet;
printf ("\ninsira o nome:");
gets (Livros[i].autor); //writer
flush_toilet;
printf ("\ninsira o preco :");
scanf ("%f",&Livros[i].prec);//price
flush_toilet;
}
return Livros;
}
And then later use the return in main ():
void main (){
struct livro *Livros = NULL;
int qtd=-1, selec=1, nacima=-1;
float med=-1;
while (selec!=0){
// Snip
switch (selec){
// snip
case 1:
{
if (Livros != NULL)
{
free(Livros);
Livros = NULL;
}
Livros = cadastro(&qtd);
}
break;
You also need to check the return values of scanf() and gets() in case there is no more input or invalid input, and have a default case in the event the user enters an invalid value for selec. You should also consider replacing gets() with fgets() to prevent buffer overruns. But the immediate cause of the crash is the uninitialized variable. Presumably your compiler also reports a similar warning, and if it does, warnings like this should always be fixed.