//Ordenacao por insercao/selecao
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
int vet[10]={8,16,34,13,19,7,45,3,12,9},a,b,aux;
void selecao();
int pesquisar_bin(int,int,int,int);
int main (){
int opt=0,num,max;
char continuar;
printf("ESCOLHA O METODO DE ORDENACAO:\n\
1- INSERCAO\n\
2- SELECAO\n\
3- SAIR\n");
do{
scanf("%d",&opt);
}while(opt!=1 && opt!=2 && opt!=3);
switch(opt){
case 1:
break;
case 2:
selecao();
break;
case 3:
exit(1);
break;
}
printf("\n\n1- PESQUISA SEQUENCIAL\n\n\
2- PESQUISA BINARIA\n");
do{
aux=0;
scanf("%d",&aux);
}while(aux!=1&&aux!=2);
printf("DIGITE O VALOR A SER PESQUISADO:\n");
scanf("%d",&num);
else if(aux==2){
max=sizeof(vet)/sizeof(int);
pesquisar_bin(vet[max],0,max,num);
}
}
//ORDENACAO POR SELECAO
void selecao(){
int i=1;
do{
b=0;
for (a=0;a<9;a++){
if(vet[a+1]<vet[a]){
aux=vet[a];
vet[a]=vet[a+1];
vet[a+1]=aux;
b=1;
}
}
if(b==1){
printf("Fase %d: [",i);
for(a=0;a<10;a++){
printf("%d ",vet[a]);
}
printf("]\n\n");
i++;
}
}while(b==1);
}
//PESQUISA BINARIA
int pesquisar_bin(int vetor[],int ini,int fim,int numero){
int pos;
pos=((fim-ini)/2)+ini;
if (ini>fim){
printf("Valor %d nao encontrado no vetor\n",numero);
return 0;
}
if(numero>vet[pos]){
return (pesquisar_bin(vet,pos+1,fim,numero));
}
else if(numero<vet[pos]){
return (pesquisar_bin(vet,ini,pos-1,numero));
}
else if(numero==vet[pos]){
printf("O valor %d se encontra na posicao %d do vetor.",numero,pos);
return 0;
}
}
I've been doing some exercises of C but I really don't understand why dev C++ is returning this error.
I already tried to do many things like to change the reference including a point and other things.
C:\Users\ANONYM~1\AppData\Local\Temp\ccguUdp9.o ordenacao.cpp:(.text+0x128):
undefined reference to `pesquisar_bin(int, int, int, int)'
\Mac\Home\Desktop\EXERCICIOS ED\collect2.exe [Error] ld returned 1
exit status
Your declaration and use of pesquisar_bin, does not match your implementation. As #JMichelB points out, vetor is declared to be an int and you pass it an int when calling pesquisar_bin, but your implementation defines vetor as an int[]. In the absence of an MCVE, that's the best we can surmise at this point in time.
Your implementation of pesquisar_bin is ignoring the vetor parameter and using the vet variable from file scope instead. The code is a mess due to your thrashing about and not actually posting an MCVE. Pass vet to pesquisar_bin and change the implementation to use the vetor parameter.
Related
I'm new to C, I've already searched and I haven't found an answer, but I've been trying to get the program to give me a list with the name of the products typed in by the user followed by the sum of all prices and I've found the error:
clang-7 -pthread -lm -o main main.c
/tmp/main-7440c0.o: In function `main':
main.c:(.text+0x12b): undefined reference to 'N'
main.c:(.text+0x164): undefined reference to 'Digitanome'
main.c:(.text+0x17f): undefined reference to 'Lista'
clang-7: error: linker command failed with exit code 1 (use -v to see invocation)
exit status 1
The code I've been trying is this one:
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
extern char (N[][40]);
int i;
char p;
int cod,cont, soma2;
char soma[100];
int Digitanome( char [][40], int );
void Lista( char [100][40], int );
typedef struct {
char produto[30];
char seçao [30];
float preco;
int cargo;
}Supermercado;
Supermercado compra;
int main(void)
{
char Nome[100][40] = { '\0' };
int qtdNomes = 0;
soma2 = 0;
do{
printf("\n\nEm qual seção está seu produto?");
printf("\n1-Frutas \n2-Doces \n3-Material de Limpeza\n --> ");
scanf("%d",&cod);
if(cod == 1){
*compra.seçao = *strcpy(compra.seçao,"Frutas");
}
if(cod == 2){
*compra.seçao = *strcpy(compra.seçao, "Doces");
}
if(cod == 3){
*compra.seçao = *strcpy(compra.seçao,"Material de Limpeza");
}
int Digitanome(char N[][40], int i);
{
printf("Informe o produto que você quer nesta seção: \n");
scanf("%s", & *N[i]);
*compra.produto = Digitanome( Nome, qtdNomes );
Lista( Nome, qtdNomes );
return ++i;
}
return 0;
printf("Informe o preço do produto: \n");
scanf("%f", &compra.preco);
soma2 = soma2 + compra.preco;
printf("\nDeseja mais algum produto? \n4-Sim \n0-Não, sair \n --> ");
scanf("%d",&cont);
}while(cont == 4);
{
if (cont == 0)
printf("\nFIM DAS COMPRAS!\n");
void Lista(char p[100][40], int i);{
int j = 0;
for (; j < i; j++ )
printf("\nSeus produtos são:%s\n", compra.produto);
}
printf("Essa compra está custando: %i \n", soma2);
}
}
Can anyone explain to me what is happening and how to solve it?
Several problems:
extern char (N[][40]);
You declare N as extern without initialization so you would also need to delcare it in another module with initialization. But you don't actually ever use the variable N. You have N[][40] as an argument to Digitanome. Once you fix item numbers 2 and 3 below, you can remove extern char (N[][40]); completely.
You define Digitanome and Lista inside main(). You need to define them outside of main().
You have semicolons at the end of Digitanome and Lista function definitions. You need to remove those.
You have code following the return 0 statement.
You call Digitanome from inside Digitanome. That is probably not what you want.
Once you fix those problems, you will probably find more.
As Jim mentioned, there is some syntax error in your code you need to fix.
I could not understand the logic of your code so if you still need help, comment to me so that we can do it together!
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
extern char (N[][40]); int i; char p; int cod,cont, soma2; char soma[100];
int Digitanome( char [][40], int ); void Lista( char [100][40], int ); int qtdNomes = 0;
char Nome[100][40] = { '\0' };
typedef struct { char produto[30]; char seçao [30]; float preco; int cargo; }Supermercado;
Supermercado compra;
int main(void) {
soma2 = 0; do{
printf("\n\nEm qual seção está seu produto?");
printf("\n1-Frutas \n2-Doces \n3-Material de Limpeza\n --> ");
scanf("%d",&cod);
if(cod == 1){
*compra.seçao = *strcpy(compra.seçao,"Frutas");
}
if(cod == 2){
*compra.seçao = *strcpy(compra.seçao, "Doces");
}
if(cod == 3){
*compra.seçao = *strcpy(compra.seçao,"Material de Limpeza");
}
return 0;
printf("Informe o preço do produto: \n");
scanf("%f", &compra.preco);
soma2 = soma2 + compra.preco;
printf("\nDeseja mais algum produto? \n4-Sim \n0-Não, sair \n --> ");
scanf("%d",&cont); }while(cont == 4); {
if (cont == 0)
printf("\nFIM DAS COMPRAS!\n");
printf("Essa compra está custando: %i \n", soma2); } }
int Digitanome(char N[][40], int i)
{
printf("Informe o produto que você quer nesta seção: \n");
scanf("%s", & *N[i]);
*compra.produto = Digitanome( Nome, qtdNomes );
Lista( Nome, qtdNomes );
return ++i;
}
void Lista(char p[100][40], int i) { int j = 0; for (; j < i; j++ )
printf("\nSeus produtos são:%s\n", compra.produto); }
Here is the main function:
int main (void){
tProyecto proyecto; /*Proyecto a gestionar*/
int opcion; /*Opción del menú elegida*/
encabezado();
inicializarProyecto (proyecto);
do
{
opcion=menu();
switch (opcion)
{
case 1: altaInvestigadorEnProyecto (proyecto);
break;
case 2: listarProyecto (proyecto);
break;
case 3: asignarTareasAInvestigador (proyecto);
break;
case 4: borrarInvestigadorDelProyecto (proyecto);
break;
case 5: printf ("\nAdios. Gracias por utilizar este programa");
break;
default: printf ("\nNo es una opcion correcta. Por favor, introduzca un numero entre 1 y 5.");
}
}while (opcion!=5);
return 0;
}
Here the .h file
typedef char tDNI[MAX_DNI];
typedef char tNombre[MAX_NOMBRE];
typedef struct {
tNombre nombre;
tDNI dni;
tTareasAsignadas tareas;
} tInvestigador;
typedef struct {
tInvestigador investigador;
int ocupado; /*1 ocupado, 0 no ocupado */
} tCelda;
typedef tCelda tProyecto [MAX_INVES];
/* Extern functions prototype */
extern void altaInvestigadorEnProyecto(tProyecto* proyecto);
extern void listarProyecto(tProyecto* proyecto);
extern void inicializarProyecto(tProyecto* proyecto );
extern void borrarInvestigadorDelProyecto(tProyecto* proyecto);
extern void asignarTareasAInvestigador(tProyecto* proyecto);
The problem in CodeBlocks words is "warning: passing argument 1 of 'inicializarProyecto' from incompatible pointer type--note: expected 'struct tCelda (*)[3]' but argument is of type 'struct tCelda *"
I understand this means that the function expects a struct array but I'm sending just a struct to it. I don't know how to design it so it works that way. The problem is on the calling of the functions in the main and in the "extern void" functions. I'd really appreciate if someone could tell me how to do it.
This are the functions where the pointer is used:
void altaInvestigadorEnProyecto(tProyecto* proyecto){
tNombre nombre;
tDNI dni;
int salida = 0;
if (haySitioEnProyecto(proyecto, &salida) == 1){
printf("\nIntroduzca el investigador a dar de alta: \n");
scanf("%s\n", nombre);
if (strncmp(proyecto[salida]->investigador.nombre, nombre, MAX_NOMBRE)
!= 0){
printf("\nIntroduzca el DNI del investigador a dar de alta: \n");
scanf("%s\n", dni);
proyecto[salida]->ocupado = 1;
strncpy(proyecto[salida]->investigador.nombre, nombre, MAX_NOMBRE);
strncpy(proyecto[salida]->investigador.dni, dni, MAX_DNI);
}
}
}
int haySitioEnProyecto(tProyecto * proyecto, int * sitio){
int ok = 0;
int i;
for (i=0; (i<MAX_INVES) && (ok == 0); i++){
if (proyecto[i]->ocupado == 0){
ok = 1;
*sitio = i;
}
}
return ok;
}
void listarProyecto(tProyecto * proyecto){
int i;
printf("/nProyecto: \n");
for(i=0; i<MAX_INVES; i++){
if (proyecto[i]->ocupado == 1){
printf("/nInvestigador:\n");
printf("/n/tNombre: %s: \n", proyecto[i]->investigador.nombre);
printf("/n/tDNI: %s: \n", proyecto[i]->investigador.dni);
printf("/n/tTareas:\n");
listarTareasAsignadas(proyecto[i]->investigador.tareas);
}
}
}
void asignarTareasAInvestigador(tProyecto * proyecto){
tDNI dni;
int posicion = 0;
int aniadir = 0;
int i;
listarProyecto(proyecto);
printf("\nIntroduzca el DNI del investigador al que se quiere asignar
tareas: \n");
scanf("%s\n", dni);
if (buscarInvestigadorPorDNI(proyecto, dni, &posicion) == 1){
for (i = 0; i < (MAX_TAREAS - proyecto[posicion]-
>investigador.tareas.numeroTareasAsignadas); i++){
printf("/n¿Quiere aniadir una tarea?: (0: no quiero; 1: quiero)\n");
scanf("%u\n", &aniadir);
if (aniadir == 1){
if (proyecto[posicion]-
>investigador.tareas.numeroTareasAsignadas < MAX_TAREAS){
aniadirTarea(&(proyecto[posicion]->investigador.tareas));
}
}
}
}
}
int buscarInvestigadorPorDNI(tProyecto * proyecto, tDNI dni, int * posicion)
{
int ok = 0;
int i;
for (i = 0; (i < MAX_INVES) && (ok == 0); i++){
if (strncmp(proyecto[i]->investigador.dni, dni, MAX_DNI) == 0){
ok = 1;
*posicion = i;
}
}
return ok;
}
void borrarInvestigadorDelProyecto(tProyecto * proyecto){
tDNI dni;
int posicion = 0;
listarProyecto(proyecto);
printf("\nIntroduzca el DNI del investigador que quiere eliminar: \n");
scanf("%s\n", dni);
if (buscarInvestigadorPorDNI(proyecto, dni, &posicion) == 1){
proyecto[posicion]->ocupado = 0;
strncpy(proyecto[posicion]->investigador.nombre, "", MAX_NOMBRE);
strncpy(proyecto[posicion]->investigador.dni, "", MAX_DNI);
inicializarTareasAsignadas(&(proyecto[posicion]->investigador.tareas));
}
}
Well the problem is - you have called it wrong.
inicializarProyecto (proyecto);
will be
inicializarProyecto (&proyecto);
That will solve the warning message. First one had type of tCelda * but the second one will be tCelda (*)[MAX_INVES] which in turn matches with the pointer to the typedef-ed type tProyecto (which is basically tCelda [MAX_INVES]).
That means wherever you have tProyecto * proyecto pass &proyecto and then in the functions you will access it like this
(*proyecto)[i].ocupado = 1;
or
proyecto[0][i].ocupado = 1;
where i is obviously i>=0 and i<=MAX_INVES-1.
#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?
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 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.