Thread: Problems working with Pointers

  1. #1
    Registered User
    Join Date
    Jun 2019
    Posts
    2

    Problems working with Pointers

    Pls What am I doing wrong.

    I am using am array to make a data structure were I save the data that cames from the user.

    That Part is working,

    But when I try to show the data intruduced I get strange results, as if the data hasn' t been saved correctly.

    First file:

    Code:
    #include <stdio.h>
    #include <locale.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    #include "biblioteca.h"
    #include "records.h"
    
    
    int add_rec(){
    
    
         char ch;
         struct records aux;
    
    
         /* Lê os elementos e cria o registo antes do o introduzir na base de dados */
         printf("(Obrigatório) Titulo : ");
         gets(aux.titulo);
    
    
         printf("Sub Titulo : ");
         gets(aux.subtitulo);
    
    
         printf("Autor : ");
         gets(aux.autoria);
    
    
         printf("(Obrigatório) Local de Edição : ");
         gets(aux.local_edicao);
    
    
         printf("Editora : ");
         gets(aux.editora);
    
    
         //Alterar
         printf("Ano de edição : ");
         scanf("%d",&(aux.ano_edicao));
    
    
         /* Código para limpar o buffer antes de ler o caracter */
         while ((ch = getchar()) != '\n' && ch != EOF) {}
         printf("Cota : ");
         gets(aux.cota);
    
    
         printf("(Obrigatório) Preço : ");
         scanf("%f",&(aux.preco));
    
    
         aux.status = '*';
    
    
         if (add_record(&aux) == 0){
            printf("Registo inserido\n");
            return 0;
         } else {
            printf("Erro a inserir registo\n");
            return -1;
         }
    }
    
    
    void menu(){
    
    
         char option, ch;
    
    
         option = '0';
    
    
         while (option != 'X'){
             printf("\n");
             printf("--------------\n");
             printf("Menu Principal\n");
             printf("--------------\n");
             printf("\n\n");
    
    
             printf("A - Adicionar Registo\n");
             printf("B - Editar Registo\n");
             printf("C - Remover Registo\n");
             printf("P - Pesquisas\n");
             printf("L - Listagens\n");
             printf("I - Importar Registos\n");
             printf("E - Exportar Registos\n");
             printf("Z - !!!Reinicializar a Base Bibligráfica!!!\n");
             printf("\n\n");
             printf("X - Sair\n");
             printf("\n\n");
             printf("Opção : ");
    
    
             scanf("%c",&option);
             /* Código para limpar o buffer antes de ler o caracter */
             while ((ch = getchar()) != '\n' && ch != EOF) {}
    
    
             switch(option){
                    case 'A':
                         add_rec(); /* Criar verificação da introdução dos dados */
                         /* Código para limpar o buffer antes de ler o caracter */
                         while ((ch = getchar()) != '\n' && ch != EOF) {}
                         break;
                    case 'B':
                         break;
                    case 'C':
                         break;
                    case 'P':
                         menu_pesquisas();
                         break;
                    case 'L':
                         menu_listagens();
                         break;
                    case 'I':
                         break;
                    case 'E':
                         break;
                    case 'Z':
                         break;
                    case 'X':
                         return;
                         break;
                    default:
                         printf("-----------------\n");
                         printf("Opção inexistente\n");
                         printf("-----------------\n\n\n");
             }
         }
    
    
    } /* Function menu - end  */
    
    
    void menu_pesquisas(){
    
    
         char option, ch;
    
    
         option = '0';
    
    
         while (option != 'X'){
             printf("\n");
             printf("--------------\n");
             printf("Menu Pesquisas\n");
             printf("--------------\n");
             printf("\n\n");
    
    
             printf("1 - Pesquisar: por Título\n");
             printf("2 - Pesquisar: por Autoria\n");
             printf("3 - Pesquisar: por Listagens\n");
             printf("\n\n");
             printf("X - Sair\n");
             printf("\n\n");
             printf("Opção : ");
    
    
             scanf("%c",&option);
             /* Código para limpar o buffer antes de ler o caracter */
             while ((ch = getchar()) != '\n' && ch != EOF) {}
    
    
             switch(option){
                    case '1':
                         break;
                    case '2':
                         break;
                    case '3':
                         break;
                    case 'X':
                         return;
                         break;
                    default:
                         printf("-----------------\n");
                         printf("Opção inexistente\n");
                         printf("-----------------\n\n\n");
             }
         }
    }
    
    
    void menu_listagens(){
    
    
         char option, ch;
    
    
         option = '0';
    
    
         while (option != 'X'){
             printf("\n");
             printf("--------------\n");
             printf("Menu Listagens\n");
             printf("--------------\n");
             printf("\n\n");
    
    
             printf("1 - Listagem: Sequencial\n");
             printf("2 - Listagem: Ordenada por Título\n");
             printf("3 - Listagem: Ordenada por Autoria\n");
             printf("\n\n");
             printf("X - Sair\n");
             printf("\n\n");
             printf("Opção : ");
    
    
             scanf("%c",&option);
             /* Código para limpar o buffer antes de ler o caracter */
             while ((ch = getchar()) != '\n' && ch != EOF) {}
    
    
             switch(option){
                    case '1':
                         mostra_registo();
                         break;
                    case '2':
                         break;
                    case '3':
                         break;
                    case 'X':
                         return;
                         break;
                    default:
                         printf("-----------------\n");
                         printf("Opção inexistente\n");
                         printf("-----------------\n\n\n");
             }
         }
    }
    
    
    int main(){
    
    
         setlocale(LC_ALL, "");
    
    
         menu();
    
    
         return 0;
    
    
    }
    Second File
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include "records.h"
    
    
    /* Tenho que criar uma variável que é um array de tamanho desconhecido, sempre que ler uma registo
     * terei que alocar memória para o guardar no registo */
    struct records *rec;
    int elementos = 0; /* Numero de elementos no registo */
    
    
    int add_record(struct records *elem){
    
    
        struct records *temp;
    
    
        temp = realloc(rec, sizeof(struct records *));
        /* Verifica se houve boa alocação de memória */
        if (temp == NULL){
           strcpy(erro,"Erro na alocação de memória\n");  /* Especifica o erro */
           return -1; /* Indica erro */
        }
    
    
        elementos += 1;
        rec = temp;
    
    
        temp = temp + elementos;
    
    
    
    
    
    
        /* Falta verificar se o registo é duplicado */
    
    
        /* cópia de cada um dos elementos */
        strcpy(temp->titulo , elem->titulo);
        strcpy(temp->subtitulo , elem->subtitulo);
        strcpy(temp->autoria , elem->autoria);
        strcpy(temp->local_edicao , elem->local_edicao);
        strcpy(temp->editora , elem->editora);
        strcpy(temp->cota , elem->cota);
        temp->status  = '*';
        temp->ano_edicao = elem->ano_edicao;
        temp->preco = elem->preco;
    
    
             printf("%s",temp->titulo);
             if (strlen(temp->subtitulo) > 0)
                  printf(" : %s",temp->subtitulo);
             if (strlen(temp->autoria) > 0)
                  printf(" / %s",temp->autoria);
             printf(". ");
             printf("%s",temp->local_edicao);
             if (strlen(temp->editora) > 0)
                printf(" : %s",temp->editora);
             printf(", %d",temp->ano_edicao);
             printf(". ");
             if (strlen(temp->cota) > 0)
                  printf("Cota: %s",temp->cota);
             printf(" - Preco: %.2f",temp->preco);
             printf(".\n");
    
    
        return 0; /* Sem erros */
    
    
    }
    
    
    void mostra_registo(){
    
    
        struct records *temp;
        //Fails to show things right why????
        int i;
    
    
        temp = rec;
    
    
        for (i = 1; i < elementos + 1; i++){
             temp++;
             printf("%s",temp->titulo);
             if (strlen(temp->subtitulo) > 0)
                  printf(" : %s",temp->subtitulo);
             if (strlen(temp->autoria) > 0)
                  printf(" / %s",temp->autoria);
             printf(". ");
             printf("%s",temp->local_edicao);
             if (strlen(temp->editora) > 0)
                printf(" : %s",temp->editora);
             printf(", %d",temp->ano_edicao);
             printf(". ");
             if (strlen(temp->cota) > 0)
                  printf("Cota: %s",temp->cota);
             printf(" - Preço: %.2f",temp->preco);
             printf(".\n");
        }
    }
    Last needed file

    Code:
    /* Estrutura de dados */
    
    
    struct records{
    
    
           /* As variáveis de texto tem tamanho fixo, reduzindo a complexidade do programa */
           char titulo[120];
           char subtitulo[120];
           char autoria[80];
           char local_edicao[30];
           char editora[30];
           int ano_edicao;
           char cota[30];
           float preco;
           char status;
    
    
    };
    
    
    /* Variável onde se guardam os erros */
    char erro[100];
    
    
    /* Funções */
    int add_record(struct records *elem);
    void mostra_registo();

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,249
    The two immediate fixes that I suggest:
    • Stop using global variables, i.e., write your functions to have the appropriate parameters instead. Global variables make it more difficult for you to reason about your program.
    • Stop using gets, e.g., use fgets but keep in mind that fgets stores the newline entered if there is space for it. gets is inherently vulnerable to buffer overflow and has been removed from the C standard.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jun 2019
    Posts
    2
    The global variables declared, are there to be seen in the all program.
    They are:
    - Data Structure
    - Number of elements in data structure.

    About the get, it has been replaced and work fine, so far.

    The code had been compiled in windows CodeBlocks, but it's windows full of bugs.
    Now I compiled this code with and without gets in Ubuntu 14.04 and it works fine.

    I will compile the code without gets in windows later on and check the result.

    Thank you for your help.
    I think the problem may be in gets.

    Rodrigo

  4. #4
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    680
    Quote Originally Posted by Lobito View Post
    The code had been compiled in windows CodeBlocks, but it's windows full of bugs.
    Now I compiled this code with and without gets in Ubuntu 14.04 and it works fine.
    Your code may appear to work correctly with gets(), but if the data input is longer than the array, it WILL cause errors!!!

    gets() is NOT SAFE, PERIOD! Please only use fgets() but you will need to add code to remove the newline at the end of the string.

    If using gcc in Linux, please use "std=c99", or -std=c11", preferably, and turn up the warning level!

    Which compiler are you using in CodeBlocks in Windows?

  5. #5
    Registered User
    Join Date
    Apr 2019
    Posts
    662
    where would one but the -std flag in gcc - o test main.c

  6. #6
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    680
    Quote Originally Posted by cooper1200 View Post
    where would one but the -std flag in gcc - o test main.c
    Code:
    gcc -std=c11 -o test main.c

  7. #7
    Registered User
    Join Date
    Apr 2019
    Posts
    662
    ok thanks

  8. #8
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,859
    Sure, you could blame Windows, or reallocate your memory to something bigger than a pointer...

    Code:
     temp = realloc(rec, sizeof(struct records *));
    ... 
    temp = realloc(rec, sizeof(*temp));

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help working with pointers
    By satbr in forum C Programming
    Replies: 2
    Last Post: 07-06-2015, 11:15 AM
  2. Problems Working with SDL
    By LyTning94 in forum C++ Programming
    Replies: 5
    Last Post: 03-06-2011, 08:30 PM
  3. Pointers are not working correctly
    By adrian_fpd in forum C Programming
    Replies: 8
    Last Post: 11-17-2008, 07:55 PM
  4. Replies: 3
    Last Post: 09-22-2005, 10:49 AM
  5. Working with pointers...
    By CompiledMonkey in forum C++ Programming
    Replies: 2
    Last Post: 05-09-2005, 08:14 AM

Tags for this Thread