Thread: Problem with function.

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    23

    Problem with function.

    My program receives strings, then i enter a value to execute a repetition,
    I wanted the exit be "A" "B" "C" in loop.

    But ever time in the second loop i gets a erros o memory in visual studio 2008.

    Code:
    // Projeto_Veiculos.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <dos.h>
    #include <conio.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <windows.h>
    #include <iostream>
    
    /* ---------------------------------------------------------------- */
    
    // define a estrutura do processo
    struct _no 
    {
    	struct _no *anterior;
    	char nome[40];
    	struct _no *proximo;
    };
    
    /* ---------------------------------------------------------------- */
    
    typedef struct _no No;
    
    // define um ponteiro para o numero raiz
    No *Raiz=NULL;
    
    // define um ponteiro para o ultimo numero
    No *Ultimo=NULL;
    
    /* ---------------------------------------------------------------- */
    
    void Insere(char *nome) 
    {
    	No *Atual;
    	No *NoAnterior;
    	No *NoPosterior;
    	No *NovoNo;
    
    	// verifica se o nó na raiz é nulo, que é o caso quando a lista está vazia.
    	// Se for, cria nó raiz com os dados fornecidos e faz o último nó
    	// coincidir com ele
    	if (Raiz==NULL) 
    	{
    		Raiz = (No *)malloc(sizeof(No));
    		strcpy (Raiz->nome,nome);
    		Raiz->proximo = NULL;
    		Raiz->anterior = NULL;
    		Ultimo = Raiz;
    	}
    	else 
    	{  // se já houver raiz
    
    		// percorre a lista duplamente encadeada, comecando da raiz.
    		// Inicialmente, não há nó anterior
    		NoAnterior = NULL;
    		Atual = Raiz;
    		while (Atual!=NULL) 
    		{
    			if (strcmp(Atual->nome,nome)>=0) break; // se o nó atual é igual
    			// se superior,
    			// pára
    			else 
    			{
    				NoAnterior = Atual;
    				Atual = Atual->proximo;
    			}
    		}
    
    		if (Atual != NULL) // só faz a comparação abaixo se existe o nó Atual
    			if (strcmp(Atual->nome,nome)==0) 
    			{
    				printf ("\n\n Nome ja existente!\n");
    				printf ("\n\n\n\n ");
    				system("pause");
    				system("cls");
    
    				return;
    			}
    
    			// agora, iremos inserir o novo nó entre o nó atual e o nó anterior
    			NoPosterior = Atual;
    
    			// aloca memória para o novo nó
    			NovoNo = (No *)malloc(sizeof(No));
    
    			// coloca dados no nó a ser inserido
    			strcpy (NovoNo->nome,nome);
    
    
    			// atualiza ponteiros do novo nó
    			NovoNo->proximo = NoPosterior;
    			NovoNo->anterior = NoAnterior;
    
    			// atualiza ponteiros dos nós vizinhos
    			if (NoAnterior != NULL)
    				NoAnterior->proximo = NovoNo;
    			if (NoPosterior != NULL)
    				NoPosterior->anterior = NovoNo;
    
    			// verifica se o novo nó foi inserido no início ou no fim da lista
    			// se foi, atualiza referências
    			if (NovoNo->anterior == NULL)
    				Raiz = NovoNo;
    			if (NovoNo->proximo == NULL)
    				Ultimo = NovoNo;
    	}
    }
    
    /* ---------------------------------------------------------------- */
    
    void Lista() 
    {
    	No *Atual;
    	printf ("\n");
    	// percorre a lista duplamente encadeada desde a raiz
    	Atual = Raiz;
    	while(Atual!=NULL) 
    	{
    		printf ("\n Processo: %s\n",Atual->nome);
    		Atual=Atual->proximo;
    	}
    	printf ("\n\n\n\n ");
    	system("pause");
    	system("cls");
    }
    
    /* ---------------------------------------------------------------- */
    
    void Deleta(char *nome) 
    {
    	No *Atual;
    	No *Anterior=NULL;
    	No *Posterior;
    	//char *nomeatual;
    
    	// primeiro, percorre a lista duplamente encadeada desde a raiz
    	Atual = Raiz;
    	while (Atual!=NULL) 
    	{
    		// verifica se já encontrei ou já passei do nome procurado
    		if (strcmp(Atual->nome,nome)>=0) break;
    		else  {  // se ainda não passou
    			Anterior = Atual;
    			Atual = Atual->proximo;
    		}
    	}
    
    	if (Atual!=NULL)
    		Posterior = Atual->proximo;
    
    	// verifica se o nó atual é mesmo o nó procurado
    	if (Atual != NULL)
    		if (strcmp(Atual->nome,nome)==0) {  // se for, deleta
    			// faz com que o nó subsequente ao atual seja o subsequente ao nó
    			// anterior para manter a integridade da lista
    			if (Atual != Raiz)
    				Anterior->proximo = Atual->proximo;
    			else  // se o no atual é a raiz, atualizo a referência para a raiz
    				Raiz = Atual->proximo;
    			// faz com que a referência para o nó anterior do próximo nó seja
    			// o nó anterior ao que será deletado, para manter a integridade
    			if (Atual != Ultimo)
    				Posterior->anterior = Anterior;
    			else  // se o nó atual é o último, atualiza a referência para o último
    				Ultimo = Anterior;
    			// agora, o nó atual MÓÓÓRRÉU
    			free(Atual);
    			printf ("\n\n Nome deletado! \n\n");
    			printf ("\n\n\n\n ");
    			system("pause");
    			system("cls");
    			return;
    		}
    
    		printf("\n\n Nao achei!\n");
    		printf ("\n\n\n\n ");
    		system("pause");
    		system("cls");
    }
    
    /* ---------------------------------------------------------------- */
    
    void Executa(char *nome) 
    {		
    	int Ciclos, Qtde;
    
    	Ciclos=1;
    	Qtde=1;
    
    	if (Raiz!=NULL)
    	{
    		No *Atual;
    		Atual = Raiz;
    
    		printf("\n\n Entre com a quantidade de ciclos desejada: " ); //EXECUTA A QUANTIDADE DE REGISTRO DESEJADA
    		scanf("%i", &Qtde);
    	
    		while(Ciclos<Qtde)	//VERIFICA QUANDO ECERRA O LAÇO
    		{
    			if (Atual==Raiz)
    			{						
    				Ciclos++;
    			}
    
    			printf(" Processo: %s | Qtde: %d | Ciclo: %i \n", Atual->nome, Qtde, Ciclos-1);
    			Atual=Atual->proximo;
    			Sleep(500);
    		}					
    	}
    	else
    	{
    		printf("\n\n Nao existem processos na lista!");
    	}
    	printf("\n\n\n\n ");
    	system("pause");
    	system("cls");
    	Qtde=0;
    	Ciclos=1;
    }
    
    /* ---------------------------------------------------------------- */
    
    int main () 
    {
    	int opcao;
    	char nome[40];
    
    	do 
    	{
    		printf("\n\n ****************** MENU ****************** \n (1) -> para inserir um novo processo:\n (2) -> para excluir um processo:\n (3) -> para listar todos os processos: \n (4) -> para executar os processos: \n (0) -> para sair \n ****************************************** \n\n Opcao: ");
    		scanf("%d",&opcao);
    
    		if (opcao == 1 || opcao == 2) 
    		{
    			printf("\n\n Entre com o nome do processo: " );
    			scanf("%s",nome);
    			system("cls");
    		}
    
    		switch (opcao) 
    		{
    		case 1: 
    			{
    				Insere(nome); 
    				break;
    			}
    
    		case 2: 
    			{
    				Deleta(nome); 
    				break;
    			}
    		case 3: 
    			{
    				Lista(); 
    				break;
    			}
    		case 4: 
    			{
    				Executa(nome); 
    				break;
    			}
    
    		}
    	} while (opcao != 0);
    
    } 
    
    /* ---------------------------------------------------------------- */

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Please be more specific and point to the code in error and also show the error output.
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Registered User
    Join Date
    Aug 2008
    Posts
    23
    The error is in this part...

    Code:
    void Executa(char *nome) 
    {		
    	int Ciclos, Qtde;
    
    	Ciclos=1;
    	Qtde=1;
    
    	if (Raiz!=NULL)
    	{
    		No *Atual;
    		Atual = Raiz;
    
    		printf("\n\n Entre com a quantidade de ciclos desejada: " ); //EXECUTA A QUANTIDADE DE REGISTRO DESEJADA
    		scanf("%i", &Qtde);
    	
    		while(Ciclos<Qtde)	//VERIFICA QUANDO ECERRA O LAÇO
    		{
    			if (Atual==Raiz)
    			{						
    				Ciclos++;
    			}
    
    			printf(" Processo: %s | Qtde: %d | Ciclo: %i \n", Atual->nome, Qtde, Ciclos-1);
    			Atual=Atual->proximo;
    			Sleep(500);
    		}					
    	}
    	else
    	{
    		printf("\n\n Nao existem processos na lista!");
    	}
    	printf("\n\n\n\n ");
    	system("pause");
    	system("cls");
    	Qtde=0;
    	Ciclos=1;
    }
    i ask for a int number like 4, i for the code do "A""B""C" "A""B""C".
    but evertime he execute olny the fist loop "A""B""C" then give me a error

    Exceção de primeira chance em 0x661a984f no Estrutura de Dados.exe: 0xC0000005: Violação de acesso ao ler o local 0x00000004.
    Exceção sem tratamento em 0x661a984f no Estrutura de Dados.exe: 0xC0000005: Violação de acesso ao ler o local 0x00000004.

  4. #4
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Will Atual->nome always have a valid pointer to a string? What happens when you hit end of the chain and Atual is zero?
    Mainframe assembler programmer by trade. C coder when I can.

  5. #5
    Registered User
    Join Date
    Aug 2008
    Posts
    23
    Quote Originally Posted by Dino View Post
    Will Atual->nome always have a valid pointer to a string? What happens when you hit end of the chain and Atual is zero?
    I don't have idea of how to arrange that.
    my program entirely does is that...
    1 -enters with a String. (Work)
    2 - deletes a String. (Work)
    3 - lists all of the strings. (Work)
    4 - enters with a value, and print alternately the strings

  6. #6
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Add a condition to your WHILE clause to also check for Atual != NULL
    Mainframe assembler programmer by trade. C coder when I can.

  7. #7
    Registered User
    Join Date
    Aug 2008
    Posts
    23
    I don't know what i did wrong, but still do not work!

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Q and C are local so there's no need to set them to to anything at the end. You need to check to make sure A isn't NULL.


    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Sep 2009
    Posts
    13
    Voce eh brasileira?

  10. #10
    Registered User
    Join Date
    Aug 2008
    Posts
    23
    Quote Originally Posted by Samyx View Post
    Voce eh brasileira?
    Sou sim!!

  11. #11
    Registered User
    Join Date
    Aug 2008
    Posts
    23
    Someone can help me fix this error?

  12. #12
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    I already told you what you did wrong. Where's your updated code, with a description of what it does compared to what you want it to do?


    Quzah.
    Hope is the first step on the road to disappointment.

  13. #13
    Registered User
    Join Date
    Aug 2008
    Posts
    23
    Quote Originally Posted by quzah View Post
    I already told you what you did wrong. Where's your updated code, with a description of what it does compared to what you want it to do?


    Quzah.
    He does that...

    Option 1 - Enter a value in string [Ex. A, B, C] This Work.
    Option 2 - Delete a string. [Ex. B] Still in memory [A,C] This Work
    Option 3 - List all strngs [A,C] This Work
    Option 4 - Enter a int for execute a loop [4]
    The output i want is [A, B] 4x
    [Ex. A,C, 1] [A,C, 2] [A,C, 3] [A,C, 4]

    My error is after the 1 loop, he give a error in Atual->nome, i can´t fix this.
    Last edited by Ervilha; 09-29-2009 at 06:09 AM.

  14. #14
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    So option four just prints out your entire list four times?
    Code:
    void optionfour( int loops )
    {
        int x = 0;
        while( x++ < loops )
        {
            No *n = NULL;
            for( n = firstnode; n; n = n->next )
                printf( "%s ", n->data );
            printf( "\n" );
        }
    
    }
    Something to that effect, unless I'm confusing what you really want done.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 10-29-2008, 06:33 AM
  2. wxWidgets link problem
    By cboard_member in forum C++ Programming
    Replies: 2
    Last Post: 02-11-2006, 02:36 PM
  3. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  4. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  5. Problem with function pointers
    By vNvNation in forum C++ Programming
    Replies: 4
    Last Post: 06-13-2004, 06:49 AM