I need your help because when I print the values of atual->chave they return Symbols.
this is the code:
void mostrar(struct tLdde *l, int modo)
{
struct tItem *atual;
char *chave;
if(modo == CABECA)
{
atual = l->inicio;
while(atual != NULL)
{
chave = atual->chave;
printf("%s ", &chave);
atual = atual->proximo;
}
}
else
{
atual = l->final;
while(atual != NULL)
{
chave = atual->chave;
printf("%s ", &chave);
atual = atual->anterior;
}
}
printf("\n");
}
and this is the output:
Spea { Obam{ iPhoP{ Pott8{
use
printf("%s ", chave);
and not
printf("%s ", &chave);
remove the &
Related
hi i've been doing some coding with dynamic memory and double pointers, and work fine in the first part, but when it starts executing the second part(the second double pointer) which is exactly coded as the first one it stops working
main.c.
int main(int cant,char **argv)
{
int troden;
if(cant != 3)
{
printf("papu ta mal /n");
}
else
{
troden = archivOrden(*(argv + 1),*(argv + 2));
}
return 0;
}
function.c
#include "funciones.h"
int archivOrden(char *fileName1,char *fileName2)
{
FILE *arch1 =NULL,*arch2 = NULL;
char **vec1 = NULL;
char **vec2 = NULL;
char **aux = NULL;
int ret = 0;
int i = 0, j = 0, x = 0;
int a;
arch1=fopen(fileName1,"r");
arch2=fopen(fileName2,"r");
if(arch1 == NULL || arch2 == NULL)
{
printf("error al querer crear arch \n");
}
else
{
vec1 = (char**)malloc(sizeof(char)*1);
vec2 = (char**)malloc(sizeof(char)*1);
if(vec1 == NULL || vec2 == NULL) ret = -1;
if(ret == 0)
{
*vec1 = (char*)malloc(sizeof(char)*1);
*vec2 = (char*)malloc(sizeof(char)*1);
if(*vec1 == NULL || *vec2 == NULL) ret = -1;
if(ret == 0)
{
while(!feof(arch1))
{
*(vec1+j) = realloc(*(vec1+j),sizeof(char)*(1+i));
fread((*(vec1+j)+i),sizeof(char),1,arch1);
if(*(*(vec1+j)+i) =='\n')
{
*(*(vec1+j)+i) = '\0';
printf("%s \n",*(vec1+j));
j++;
i = 0;
vec1 = realloc(vec1,sizeof(char)*(1+j));
*(vec1+j) = (char*)malloc(sizeof(char)*(1+i));
}
else i++;
}
*(vec1+j) = realloc(*(vec1+j),sizeof(char)*(1+i));
*(*(vec1+j)+i) = '\0';
i = 0;
while(!feof(arch2))
{
*(vec2+x) = realloc(*(vec2+x),sizeof(char)*(1+i));
fread((*(vec2+x)+i),sizeof(char),1,arch2);
if(*(*(vec2+x)+i) =='\n')
{
//pongo un \0 en el final de la linea
*(*(vec2+x)+i) = '\0';
printf("%s \n",*(vec2+x));
// paso a la siguiente linea
x++;
i = 0;
vec2 = (char**)realloc(vec2,sizeof(char)*(1+x));
*(vec2+x) = (char*)malloc(sizeof(char)*(1+i));
}
else i++;
}
*(vec2+x) = realloc(*(vec2+x),sizeof(char)*(1+i));
*(*(vec2+x)+i) = '\0';
printf("paso por aca \n");
for(a = 0;a<j;a++)
{
printf("%d: %s /n",a,*(vec1+j));
}
for(a = 0;a<x;a++)
{
printf("%d: %s \n",a,*(vec2+a));
}
}
}
}
printf("finalice \n");
fclose(arch1);
fclose(arch2);
for(a = 0;a<j;a++)
{
free(*(vec1+a));
}
for(a = 0;a<x;a++)
{
free(*(vec2+a));
}
free(vec1);
free(vec2);
return ret;
}
it breaks when it starts the second while and reaches the first '/n',
but i cant understand because i do the exact same in the first while and works perfectly fine.
I have the following the following structures to define an Binary Search Tree:
typedef struct Equipo {
char nombre[50];
char marcaMoto[30];
int puntuaciones;
struct Piloto pilotos[18];
struct nodo* izquierdo;
struct nodo* derecho;
} Equipo;
typedef Equipo Arbol;
the search in the tree will be performed by the string nombre, a char [50]. For create tree and insert data I use the functions:
Equipo* CrearEquipo(Equipo* e) {
Equipo* n = (Equipo *) malloc(sizeof(Equipo));
strncpy(n->nombre, e->nombre, 50);
strncpy(n->marcaMoto, e->marcaMoto, 30);
n->puntuaciones = 0;
n->derecho = n->izquierdo = NULL;
return n;
}
void InsertarEquipo(Equipo** arbol, Equipo* e) {
if (*arbol == NULL) {
Equipo* n = CrearEquipo(e);
*arbol = n;
} else {
int comparado = strncmp(e->nombre, (*arbol)->nombre, 50);
if (comparado > 0) {
InsertarEquipo(&(*arbol)->izquierdo, e);
} else {
InsertarEquipo(&(*arbol)->derecho, e);
}
}
}
And in main i use this functions to create test elements:
Equipo* equipo = (Equipo *) malloc(sizeof(Equipo));
strcpy(equipo->nombre, "C");
strcpy(equipo->marcaMoto, "B");
Arbol *arbol = CrearEquipo(equipo);
strcpy(equipo->nombre, "B");
strcpy(equipo->marcaMoto, "B");
InsertarEquipo(&arbol, equipo);
strcpy(equipo->nombre, "A");
strcpy(equipo->marcaMoto, "B");
InsertarEquipo(&arbol, equipo);
strcpy(equipo->nombre, "E");
strcpy(equipo->marcaMoto, "B");
InsertarEquipo(&arbol, equipo);
Later, I create the recursive function for comprobate if exists in the tree:
int ExisteEquipo(Equipo* arbol, char nombre[]) {
int comparado = strncmp(arbol->nombre, nombre, 50);
if (!arbol) {
return 0;
} else if (comparado > 0) {
printf("Menor ");
return ExisteEquipo(arbol->izquierdo, nombre);
} else if (comparado < 0) {
printf("Mayor ");
return ExisteEquipo(arbol->derecho, nombre);
} else {
printf("Igual ");
return 1;
}
}
(The printf's are for test). When I call the exists function with:
void DeterminarExistencia(Equipo* arbol, char nombre[50]) {
if (ExisteEquipo(arbol, nombre)) {
printf("El nodo %s existe. \n", nombre);
} else {
printf("El nodo %s no existe. \n", nombre);
}
}
DeterminarExistencia(arbol, "E");
DeterminarExistencia(arbol, "C");
DeterminarExistencia(arbol, "H");
DeterminarExistencia(arbol, "B");
but I always get the error: Violación de segmento (core dumped) [Núcleo vaciado a un archivo]
I think the problem is here:
int comparado = strncmp(arbol->nombre, nombre, 50);
You are asking if arbol is null after operating with it with the line above, so if it is null you are accessing a wrong memory address and that is causing the error.
Put it like this:
if (!arbol) {
return 0;
int comparado = strncmp(arbol->nombre, nombre, 50);
Spanish:
Básicamente cambia el orden de lo que te he dicho arriba y deberia funcionar.
right now i'm trying to build a simple program as my homework for college, this was supposed to be a simple code but i'm learning c just now and i'm having a really bad time trying to learn it, anyways, this code should be able to add to add, remove, show and clear some numbers on the console, a list(i dont know if it's called that way in english), but 1 thing that i can't do and i have been researching and tryed to figure out is in how to put a limit on this list, exactly 20 numbers.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *prox;
};
typedef struct node Fila;
int t;
int menu(void);
void opcao(Fila *f, int op);
void inicia(Fila *f);
int vazia(Fila *f);
Fila *aloca();
void insere(Fila *f);
Fila *retira(Fila *f);
void exibe(Fila *f);
void libera(Fila *f);
void liberar_mem(Fila *f);
int main(void)
{
Fila *f = (Fila *)malloc(sizeof(Fila));
if (!f)
{
printf("Sem memoria disponivel!\n");
exit(1);
}
else
{
inicia(f);
int opt;
do
{
opt = menu();
opcao(f, opt);
} while (opt);
free(f);
return 0;
}
}
int menu(void)
{
int opt;
printf("Escolha a opcao\n");
printf("0. Sair\n");
printf("1. Zerar solicitacoes\n");
printf("2. Exibir solicitacoes\n");
printf("3. Inserir o numero da solicitacao\n");
printf("4. Remover solicitacao\n");
printf("Opcao: ");
scanf("%d", &opt);
return opt;
}
void opcao(Fila *f, int op)
{
Fila *tmp;
switch (op)
{
case 0:
liberar_mem(f);
break;
case 1:
libera(f);
inicia(f);
break;
case 2:
exibe(f);
break;
case 3:
insere(f);
break;
case 4:
tmp = retira(f);
if (tmp != NULL)
{
printf("Solicitacao removida: %3d\n\n", tmp->num);
free(tmp);
}
break;
default:
printf("Comando invalido\n\n");
}
}
void inicia(Fila *f)
{
f->prox = NULL;
t = 0;
}
int vazia(Fila *f)
{
if (f->prox == NULL)
return 1;
else
return 0;
}
Fila *aloca()
{
Fila *novo = (Fila *)malloc(sizeof(Fila));
if (!novo)
{
printf("Sem memoria disponivel!\n");
exit(1);
}
else
{
printf("Insira o numero da solicitacao: ");
scanf("%d", &novo->num);
return novo;
}
}
void insere(Fila *f)
{
Fila *novo = aloca();
novo->prox = NULL;
if (vazia(f))
f->prox = novo;
else
{
Fila *tmp = f->prox;
while (tmp->prox != NULL)
tmp = tmp->prox;
tmp->prox = novo;
}
t++;
}
Fila *retira(Fila *f)
{
if (f->prox == NULL)
{
printf("Lista de solicitacoes ja esta vazia\n");
return NULL;
}
else
{
Fila *tmp = f->prox;
f->prox = tmp->prox;
t--;
return tmp;
}
}
void libera(Fila *f)
{
if (f->prox == NULL)
{
printf("Lista de solicitacoes ja esta vazia\n");
Fila *proxNode, *atual;
atual = f->prox;
while (atual != NULL)
{
proxNode = atual->prox;
free(atual);
atual = proxNode;
}
}
else
{
if (!vazia(f))
{
Fila *proxNode, *atual;
atual = f->prox;
while (atual != NULL)
{
proxNode = atual->prox;
free(atual);
atual = proxNode;
}
}
}
}
void exibe(Fila *f)
{
if (vazia(f))
{
printf("Nenhuma solicitacao cadastrada!\n\n");
return;
}
Fila *tmp;
tmp = f->prox;
printf("Fila :");
while (tmp != NULL)
{
printf("%5d", tmp->num);
tmp = tmp->prox;
}
printf("\n ");
int count;
for (count = 0; count < t; count++)
printf(" ^ ");
printf("\nOrdem:");
for (count = 0; count < t; count++)
printf("%5d", count + 1);
printf("\n\n");
}
void liberar_mem(Fila *FILA)
{
if (!vazia(FILA))
{
Fila *proxNode, *atual;
atual = FILA->prox;
while (atual != NULL)
{
proxNode = atual->prox;
free(atual);
atual = proxNode;
}
}
}
You could use a global variable that keeps track of the current length of the list and return an error message when someone tries to expand the list beyond the limit.
However, while global variables are fine for simple programs, it's considered good style for larger programs to rely upon them as little as possible.
Therefore, I'd recommend using a "list header" object. For example,
#define MAX_LIST_LENGTH 20
struct list_header {
Fila *start_of_list;
unsigned int current_length;
};
I have a problem on the function ProcuraArvoreApaga which is a TreeSearchDelete function. I can't delete anything and when I try to delete the root it gives me a breakpoint.
When I try to delete the root I get the folowing breakpoint:
Exception thrown: read access violation.
raiz was 0xCCCCCCCC.
Here is the full code if you want to try by yourself or help me.
I use Visual Studio 2015
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
typedef struct tree *Arvore;
struct tree {
Arvore left;
Arvore right;
int *valor;
};
void DestruirNode(Arvore *raiz);
void ProcuraArvoreApaga(Arvore *raiz, int *value);
Arvore CriarArvore(int value) {
Arvore node;
if ((node = (Arvore)malloc(sizeof(struct tree))) == NULL) {
return NULL;
}
if ((node->valor = (int*)malloc(sizeof(int))) == NULL) {
return NULL;
}
*node->valor = value;
node->left = NULL;
node->right = NULL;
return node;
}
void DestruirArvore(Arvore *node) {
free((*node)->valor);
free(*node);
*node = NULL;
}
void Inserir(Arvore *raiz, int value) {
Arvore node = *raiz;
Arvore anterior = NULL;
if (*raiz == NULL) {
*raiz = CriarArvore(value);
return;
}
else {
while (node != NULL) {
anterior = node;
if (*node->valor > value) {
node = node->left;
}
else if (*node->valor < value) {
node = node->right;
}
else {
return;
}
}
if (*anterior->valor > value) {
anterior->left = CriarArvore(value);
}
else {
anterior->right = CriarArvore(value);
}
}
}
void ImprimirArvore(Arvore raiz, int nivel) {
int i;
if (raiz == NULL) {
for (i = 0; i < nivel; i++) {
printf("\t");
}
printf("*\n");
return;
}
ImprimirArvore(raiz->right, nivel + 1);
for (i = 0; i < nivel; i++) {
printf("\t");
}
printf("%d\n", *raiz->valor);
ImprimirArvore(raiz->left, nivel + 1);
}
Arvore Minimo(Arvore *raiz) {
Arvore node = *raiz;
while (node->left != NULL) {
node = node->left;
}
return node;
}
void DestruirNode(Arvore *raiz) {
Arvore node = *raiz;
if ((*raiz)->left == NULL && (*raiz)->right == NULL) {
DestruirArvore(raiz);
}
else if ((*raiz)->right == NULL) {
*raiz = (*raiz)->left;
DestruirArvore(raiz);
}
else {
*(*raiz)->valor = *Minimo((*raiz)->right)->valor;
ProcuraArvoreApaga(&(*raiz)->right, (*raiz)->valor);
}
}
void ProcuraArvoreApaga(Arvore *raiz, int *value) {
if (*raiz == NULL) {
return;
}
if (*(*raiz)->valor > *value) {
ProcuraArvoreApaga(&(*raiz)->right, value);
}
else if (*(*raiz)->valor < *value) {
ProcuraArvoreApaga(&(*raiz)->left, value);
}
else {
/*value = *(*raiz)->valor;*/
printf("%d", value);
DestruirNode(&raiz);
}
return 0;
}
int main(void) {
setlocale(LC_ALL, "Portuguese");
Arvore raiz = NULL;
int i = 0, escolha;
int value = NULL;
int var = NULL;
for (i = 1; i < 2; i++) {
printf("\t\tÁrvores binárias\n\n");
printf("Selecione a operação que deseja efetuar:\n");
printf("[1] Adicionar valor\n");
printf("[2] Vizualizar árvore\n");
printf("[3] Apagar valor/árvore\n");
printf("[4] Sair\n\n");
printf(">>");
scanf("%d", &escolha);
switch (escolha) {
case 1:
system("cls");
printf("Introduza o valor a adicionar à árvore:\n>>");
scanf("%d", &value);
Inserir(&raiz, value);// Adiciona na árvore
system("cls");
i = 0;
break;
case 2:
system("cls");
printf("\t\tVisualização da árvore\n\n");
ImprimirArvore(raiz, 10);// O 10 adiciona quantos níveis tem a árvore
i = 0;
break;
case 3:
system("cls");
printf("Introduza o valor que deseja apagar(um valor que não seja folha apagará os ramos e folhas abaixo dele):\n>>");
scanf("%d", &var);
ProcuraArvoreApaga(&raiz, &var);
system("cls");
i = 0;
break;
case 4:
break;
}
}
}
#include"shell.h"
int main()
{
char cInput[50];
char cCopy[50];
char *pCommand;
char pArguement[10];
bool bRun = true;
while(strcmp(pCommand, "exit"))//run untill exit
{
printf("[myshell]%% ");
cin >> cInput; //get command from user
for(int i=0; i<50; i++)
cCopy[i] = cInput[i];
//get command
pCommand = strtok(cInput, " ");
if(!strcmp(pCommand, "pwd"))
{
printf("No FUNCTIONAILITY FOR PWD! \n");
}
else if(!strcmp(pCommand, "list"))
{
printf("No FUNCTIONAILITY FOR LIST! \n");
}
else if(!strcmp(pCommand, "history"))
{
printf("No FUNCTIONAILITY FOR HISTORY! \n");
}
else if(!strcmp(pCommand, "prompt"))
{
// pCommand = strtok(cCopy, "y");
while(pCommand != NULL)
{
printf(" %s \n", pCommand);
pCommand = strtok(NULL, " ");
}
return 0;
}
else//command not found
{
printf("%s: Command not found \n", pCommand);
}
}
return 0;
}
So I'm trying to follow the example of strtok from the C standard library, but I can't figure out why I'm unable to get the next word from the cstring cInput. I was under the impression that using:
while(pCommand != NULL)
{
printf(" %s \n", pCommand);
pCommand = strtok(NULL, " ");
}
would result in getting the next words.
Any help?
Thanks!