I have few error commented after this text, i don't get what the compiler is trying to say me, the last function is in to do list i hope that's not the problem, the problem is i want to ask the user for 2 chars after that its send to a function who will compare the strings as a password and a login if the strings are the same, the program continues.
\\initializing argument 1 of int consultar(char, char)\\
\\invalid conversion from char*' to `char' \\
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void introducir_datos (struct agenda cliente[30]);
void mostrar_datos(struct agenda cliente[30]);
char consultar(char login,char password);
struct agenda{
char nombre[10];
char apellido[10];
int edad;
char direccion[20];
int codigo_postal;
};
int main(void)
{
struct agenda cliente[30];
int menu;
char con[3],login[8], password[8];
puts("\n=== Hola bienvenido a nuestra agenda en C ===\n");
puts("Login:");
gets(login);
puts("Password:");
gets(password);
**consultar(login, password);**
while ( menu != 3){
puts("\nQue quieres hacer?\n");
puts("[1]Insertar datos\n[2]Mostrar datos\n[3]Salir del programa\n");
scanf("%d", &menu);
switch(menu){
case 1:
introducir_datos(cliente);
break;
case 2:
mostrar_datos(cliente);
break;
default:
system("cls");
puts("~~~ Opcion incorrecta ~~~");
}
}
}
void introducir_datos (struct agenda cliente[30]){
int x = 0;
puts("\n=== Bienvenido a la introduccion de datos ===\n");
fflush(stdin);
system("pause");
system("cls");
puts("\nDime el nombre:\n");
fflush(stdin);
gets(cliente[x].nombre);
puts("\nDime el apellido:\n");
fflush(stdin);
gets(cliente[x].apellido);
puts("\nDime la edad:\n");
fflush(stdin);
scanf("%d",&cliente[x].edad);
puts("\nDime la direccion:\n");
fflush(stdin);
gets(cliente[x].direccion);
puts("\nDime el codigo postal:\n");
fflush(stdin);
scanf("%d",&cliente[x].codigo_postal);
x++;
}
void mostrar_datos(struct agenda cliente[30]){
for(int i=0;i<20;i++){
int x = 0;
printf("El nombre: %s \nEl apellido: %s\nEl edad: %d\nEl direccion: %s\nEl codigo postal: %d\n", cliente[x].nombre,cliente[x].apellido,cliente[x].edad,cliente[x].direccion,cliente[x].codigo_postal);
}
}
int consultar(char login, char password){
}
You need to change the consultar function (definition and implementation):
int consultar(char login, char password)
to:
int consultar(char *login, char *password)
If you use (char login, char password), it's looking for a single character. Since, by calling it with consultar(login, password);, you're using pointers to char arrays (simplified explaination), you're getting the error.
EDIT As pointed out by user "Namfuak", you should decide whether the function returns a char or an int, and have both definition and implementation be consistent.
Related
First of all, I want to explain my vocabulary of functions:
Universo: Universe
Edad: Age
Nombre: Name
Alias: Nickname
Nacionalidad: Country
Persona: Person
Insertar persona: Add Person to the Struct array
Mostrar persona: Print all the struct array elements
So I want to create a struct array and an options table in where I can choose to add persons or print them. The program max person capacity is 1000 and it checks if the person is already in the array or not, adding ir if so.
So I don't understand in first place why it doesnt print all the persons and if the persons actually are stored. Can you help me? It is a class work and I can't complicate it more that, so pointers aren't allowed. This is my code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_CAD 100
#include <string.h>
#include <ctype.h>
struct persona{
char nombre[MAX_CAD];
int edad;
char nacionalidad[MAX_CAD];
char alias[MAX_CAD];
};
int insertarPersona(struct persona universo[], int capacidad_max, struct persona nueva);
void mostrarMundo(struct persona universo[], int capacidad_max);
int main()
{
int seleccion, capacidadmax=1000, i=0;
struct persona universo[1000];
struct persona nueva;
strcpy(universo[i].nombre, "-");
strcpy(universo[i].nacionalidad, "-");
strcpy(universo[i].alias, "-");
universo[i].edad = -1;
do{
printf("1-Crear persona \^\// \n");
printf("2-Mostrar universo |. .| \n");
printf("3-Thanos-Chascar _ \ - / _ \n");
printf("4-Restaurar universo \_| |_/ \n");
printf("5-Salir \ \ \n");
printf(" __/_/__\n");
printf(" | |\n");
printf(" \ /\n");
printf(" \___/\n");
scanf("%d", &seleccion);
if(seleccion==1&&i<1000){
printf("Introduzca el nombre de la persona a añadir\n");
while(getchar()!='\n');
gets(nueva.nombre);
printf("Introduzca el alias de la persona a añadir\n");
gets(nueva.alias);
printf("Introduzca la nacionalidad de la persona a añadir\n");
gets(nueva.nacionalidad);
printf("Introduzca la edad de la persona a añadir\n");
scanf("%d", &nueva.edad);
if(insertarPersona(universo, capacidadmax, nueva)==1){
strcpy(universo[i].nombre, nueva.nombre);
strcpy(universo[i].alias, nueva.alias);
strcpy(universo[i].nacionalidad, nueva.nacionalidad);
universo[i].edad=nueva.edad;
printf("Persona añadida!\n");
i++;
}
else{
printf("El universo esta lleno o dicha persona ya esta dentro\n");
}
}else if(seleccion==2){
printf("pers. Nombre\t\t\t\t\t Alias\t\t\t\t Nacionalidad\t\t\t Edad\n");
printf("=====================================================================================================================\n");
mostrarMundo(universo, capacidadmax);
}
printf("%d",i);
}while (seleccion !=5);
return 0;
}
int insertarPersona(struct persona universo[], int capacidad_max, struct persona nueva){
capacidad_max=1000;
int espersona=0;
for(int i=0; i=='\0'&& i<capacidad_max;i++){
if ((strcmp(nueva.nombre, universo[i].nombre)&& (nueva.edad!=universo[i].edad)&& strcmp(nueva.nacionalidad, universo[i].nacionalidad)&& strcmp(nueva.alias, universo[i].alias)) !=0 && i<1000){
espersona=1;
}else {
espersona=0;
}
}
return espersona;
}
void mostrarMundo(struct persona universo[], int capacidad_max){
capacidad_max=1000;
for(int i=0; i=='\0'&&i<capacidad_max; i++){
printf("%d\t%-35s%-25s\t%-20s%10d\n", i+1, universo[i].nombre, universo[i].alias, universo[i].nacionalidad, universo[i].edad);
if(universo==0){
printf("Universo no habitado\n");
}
}
}
#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.
I'm starting to learn in C and now I'm in the chapters of structs so I'm making a simple program with switch who ask for input from the user if the user press "1" the program ask for data of a new client, and after that you can print it from another function called in a switch case "2", the problem is the printed data is totally wrong I suspect the returned data is wrong or so.
P.D: Exist any way to print only the data introduced before instead 20 times the same data?
Here's the code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct datos{
char nombre[20];
char apellido[20];
char direccion[20];
int edad[3];
long telefono[10];
}agenda;
agenda mostrar_datos();
agenda insercion_datos();
int main(void)
{
char con[3];
int menu;
puts("\n=== Bienvenido a la agenda en C ===\n");
while (!strstr(con,"si"))
{
puts("\n=== Que quieres hacer? ===\n");
fflush(stdin);
puts("\nIntroducir datos [1]\n");
puts("\nVer los datos[2]\n");
puts("\nSalir[3]\n");
scanf(" %d", &menu);
switch(menu)
{
case 1:
insercion_datos();
break;
case 2:
mostrar_datos();
break;
}
}
}
agenda insercion_datos()
{
agenda nuevo_dato;
puts("Bienvenido, vamos a introducir datos.");
puts("Dime su nombre.");
fflush(stdin);
gets(nuevo_dato.nombre);
puts("Dime su apellido.");
fflush(stdin);
gets(nuevo_dato.apellido);
puts("Dime su direccion.");
fflush(stdin);
gets(nuevo_dato.direccion);
puts("Dime su edad.");
fflush(stdin);
scanf(" %d", &nuevo_dato.edad);
puts("Dime su telefono.");
fflush(stdin);
scanf(" %d", &nuevo_dato.telefono);
}
agenda mostrar_datos()
{
int i = 0;
agenda mostrar_dato;
for (i=0;i<10;i++)
{
printf("Nombre: %s\n Apellido: %s\n Direccion: %s\n Edad: %d\n Telefono: %d\n", mostrar_dato.nombre,mostrar_dato.apellido,
mostrar_dato.direccion,mostrar_dato.edad, mostrar_dato.telefono);
}
}
I don't think this will work.
Couple of points to note here:
There is a white space in the scanf statement where you try to read the menu variable in the main()
In your function: insercion_datos() does not do anything besides creating a local variable and filling it with some data.
In your function: mostrar_datos(), the local variable is not initialized, therefore you receive no output.
Try to make a global array of `agenda' and then fill the array of structure everytime you read an input through insercion_datos(). Keep track of the number of inserts you have performed
the when you are printing using the mostrar_datos(), you can use that count and print.
I hope this resolves your doubt as to why there are no returns.