Remove array element in C

2

I have the following struct.

struct cadastro{
int codigo;
char nome[200];
char cpf[11];
char rg[10];
char tel[12];
char end[100];

}cadastro;//struct do tipo cadastro.

and the corresponding vector

struct cadastro cd[10];//vetor da funcao cadastro de cliente

My program is a mini sales terminal, I want then, at a given time, I want to inform a position (vector index) and want to delete (ie, play the items from the front index, -1. p>

//ex: vou apagar vetor na posição 3, oque está na posição 4° == 3°, oque está na posição 4° = 5°, até o final do meu vetor.

What I can not think of is how to implement this.

I tried the following

for(cod; cod < 10; cod++)
{
  cd[cod] = cd[cod+1];
}

At least that idea. but it did not happen the way I wanted and the program interrupts and returns to the menu;

    
asked by anonymous 10.05.2016 / 21:54

2 answers

2

Think about how you would do if it were a series of real objects.

Imagine 10 coins in a row on the table. You take one to relocate the others to her place. You do not start from the beginning of the queue right? You start from the position that has been removed and put one by one. The 1a is to the right of the position from which it left and will be placed in the position from which it left, the next pro place of this, etc.

So you have to have a variable with the position of the element to be removed. It has an instruction to get a user index and put in a variable. Try to find out what it is.

After this you have to make a for the end of the list by moving all the other objects to their -1 position.

See if this description helps.

Editing responding to the comment from the question author

After deleting one of the elements, you have 2 options:

  • You can create a new smaller array and copy everything there. More or less like this:

code:

struct cadastro2 cd[9];
for(int i=0;i<9;i++) cadastro2[i]=cadastro[i];
delete(array);
cadastro=cadastro2; 

I say more or less because you have to adapt this to reduce the array.

  • Or you can simply work with the array without decreasing each element and just delete the array at the end.

If you choose the 2nd option of course, some memory space will be allocated unused. But no memory leak occurs. Just the waste of a few bytes. So in your case this space is derisory and this type of preciosity takes up too much time (costly time for a company). So worry about optimizing at this level only when it's really worth it. Believe me. When you are developing "for real" there will be plenty of opportunities for you to develop your optimization and leak control talents:)

    
10.05.2016 / 23:19
1

Here is the complete solution for the customer registry using static vector:

/*
    cadastro.c
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#define ERRO_CADASTRO_CHEIO           (-2)
#define ERRO_CLIENTE_NAO_ENCONTRADO   (-1)
#define SUCESSO                       (0)

#define CLIENTES_MAX_QTD              (10)


typedef struct cliente_s cliente_t;
typedef struct cadastro_s cadastro_t;


struct cliente_s
{
    int codigo;
    char nome[100];
    char cpf[16];
    char rg[16];
    char tel[32];
    char end[200];
};


struct cadastro_s
{
    cliente_t cliente[ CLIENTES_MAX_QTD ];
    int qtd;
};


void cadastro_inicializar( cadastro_t * cad )
{
    memset( cad, 0, sizeof(cadastro_t) );
}


int cadastro_incluir_cliente( cadastro_t * cad, int cod, const char * nome, const char * cpf, const char * rg, const char * tel, const char * end )
{
    if( cad->qtd == CLIENTES_MAX_QTD )
        return ERRO_CADASTRO_CHEIO;

    cad->cliente[ cad->qtd ].codigo = cod;
    strcpy( cad->cliente[ cad->qtd ].nome, nome );
    strcpy( cad->cliente[ cad->qtd ].cpf, cpf );
    strcpy( cad->cliente[ cad->qtd ].rg, rg );
    strcpy( cad->cliente[ cad->qtd ].tel, tel );
    strcpy( cad->cliente[ cad->qtd ].end, end );

    cad->qtd++;

    return SUCESSO;
}


int cadastro_remover_cliente( cadastro_t * cad, int cod )
{
    int i, j;

    /* Para cada cliente cadastrado... */
    for( i = 0; i < cad->qtd; i++ )
    {
        /* Verifica se o cliente possui o codigo desejado */ 
        if( cad->cliente[i].codigo == cod )
        {
            /* Ajusta vetor: Desloca todos os clientes uma posicao */ 
            for( j = i; j < cad->qtd - 1; j++ )
                cad->cliente[ j ] = cad->cliente[ j + 1 ];

            /* Decrementa contador de clientes */
            cad->qtd--;

            return SUCESSO;
        }
    }

    return ERRO_CLIENTE_NAO_ENCONTRADO;
}


void cadastro_listar_clientes( cadastro_t * cad )
{
    int i = 0;

    printf("--------------------------------------------------------------------------------------------------------\n");
    printf("| Codigo |          Nome        |     CPF     |    RG    |  Telefone  |              Endereco          |\n");
    printf("--------------------------------------------------------------------------------------------------------\n");

    for( i = 0; i < cad->qtd; i++ )
        printf("|  %4d  | %-20s | %-11s | %s | %-10s | %-30s |\n", cad->cliente[i].codigo, cad->cliente[i].nome, cad->cliente[i].cpf, cad->cliente[i].rg, cad->cliente[i].tel, cad->cliente[i].end );

    printf("--------------------------------------------------------------------------------------------------------\n");
}


int main( int argc, char * argv[] )
{
    cadastro_t cad;

    /* Inicializa cadastro de clientes */
    cadastro_inicializar( &cad );

    /* Faz o cadastro de 10 clientes */
    cadastro_incluir_cliente( &cad,  10, "Albert Einstein",   "60742061477", "1234/SSP", "3234-5678", "Avenida Foobar, S/N" );
    cadastro_incluir_cliente( &cad,  20, "Isaac Newton",      "70344162907", "9898/SSP", "1234-5678", "Rua XPTO, Num. 31415" );
    cadastro_incluir_cliente( &cad,  30, "Stephen Hawking",   "78450688701", "4323/SSP", "5678-9989", "Praca Vinte, Num. 34" );
    cadastro_incluir_cliente( &cad,  40, "Leonardo da Vinci", "66814865173", "3456/SSP", "9989-1111", "Avenida Trinta, Num. 54" );
    cadastro_incluir_cliente( &cad,  50, "Galileu Galilei",   "15487316252", "9809/SSP", "9781-5555", "Rua Noventa e Tres, S/N" );
    cadastro_incluir_cliente( &cad,  60, "Ada Lovelace",      "13747920632", "1212/SSP", "9871-4532", "Rua dos Moradores, no. 100" );
    cadastro_incluir_cliente( &cad,  70, "Marie Curie",       "41325527300", "4545/SSP", "3456-1234", "Avenida da Cidade, Nem. 32" );
    cadastro_incluir_cliente( &cad,  80, "Nikola Tesla",      "12312312300", "6565/SSP", "8765-3456", "Rua Sem Nome, S/N" );
    cadastro_incluir_cliente( &cad,  90, "Michael Faraday",   "99988877700", "4444/SSP", "2323-3214", "Vila da Travessa, 123" );
    cadastro_incluir_cliente( &cad, 100, "Johannes Kepler",   "32132132111", "4343/SSP", "9898-4545", "Avenida Vazia, Numero 0" );

    /* Lista clientes cadastrados (antes das exclusoes) */
    cadastro_listar_clientes( &cad );

    /* Exclui clientes do cadastro */
    cadastro_remover_cliente( &cad, 60 );
    cadastro_remover_cliente( &cad, 70 );

    /* Lista clientes cadastrados (apos exclusoes) */
    cadastro_listar_clientes( &cad );

    return 0;
}

/* fim-de-arquivo */

However, a better way to solve your problem would be to implement a linked list instead of using a static vector.

Here is an example following your reasoning:

/*
    cadastro-lista-encadeada.c
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct cadastro_s cadastro_t;

struct cadastro_s
{
    int codigo;
    char nome[100];
    char cpf[16];
    char rg[16];
    char tel[32];
    char end[200];

    cadastro_t * prox;
};


cadastro_t * cadastro_criar( int cod, char * nome, char * cpf, char * rg, char * tel, char * end )
{
    cadastro_t * c = malloc(sizeof(cadastro_t));

    c->codigo = cod;
    strcpy( c->nome, nome );
    strcpy( c->cpf, cpf );
    strcpy( c->rg, rg );
    strcpy( c->tel, tel );
    strcpy( c->end, end );

    c->prox = NULL;

    return c;
}


void cadastro_incluir( cadastro_t ** c, cadastro_t * item )
{
    cadastro_t * p = *c;

    if( !p )
    {
        item->prox = NULL;
        *c = item;
        return;
    }

    while( p->prox )
        p = p->prox;

    item->prox = NULL;
    p->prox = item;
}


int cadastro_remover( cadastro_t ** c, int cod )
{
    cadastro_t * p = *c;
    cadastro_t * pant = NULL;

    while( p )
    {
        if( p->codigo == cod )
        {
            if( pant )
            {
                pant->prox = p->prox;
            }
            else
            {
                *c = p->prox;
            }

            free(p);

            return 0;
        }

        pant = p;
        p = p->prox;
    }

    return -1;
}


void cadastro_destruir( cadastro_t * c )
{
    cadastro_t * paux = NULL;
    cadastro_t * p = c;

    while( p )
    {
        paux = p->prox;
        free(p);
        p = paux;
    }
}


void cadastro_listar( cadastro_t * c )
{
    cadastro_t * p = NULL;

    printf("--------------------------------------------------------------------------------------------------------\n");
    printf("| Codigo |          Nome        |     CPF     |    RG    |  Telefone  |              Endereco          |\n");
    printf("--------------------------------------------------------------------------------------------------------\n");

    for( p = c; p != NULL; p = p->prox )
    {
        printf("|  %4d  | %-20s | %-11s | %s | %-10s | %-30s |\n", p->codigo, p->nome, p->cpf, p->rg, p->tel, p->end );
    }

    printf("--------------------------------------------------------------------------------------------------------\n");
}


int main( int argc, char * argv[] )
{
    cadastro_t * c = NULL;

    /* Populando lista com 10 cadastros */
    cadastro_incluir( &c, cadastro_criar(  10, "Albert Einstein",   "60742061477", "1234/SSP", "3234-5678", "Avenida Foobar, S/N" ) );
    cadastro_incluir( &c, cadastro_criar(  20, "Isaac Newton",      "70344162907", "9898/SSP", "1234-5678", "Rua XPTO, Num. 31415" ) );
    cadastro_incluir( &c, cadastro_criar(  30, "Stephen Hawking",   "78450688701", "4323/SSP", "5678-9989", "Praca Vinte, Num. 34" ) );
    cadastro_incluir( &c, cadastro_criar(  40, "Leonardo da Vinci", "66814865173", "3456/SSP", "9989-1111", "Avenida Trinta, Num. 54" ) );
    cadastro_incluir( &c, cadastro_criar(  50, "Galileu Galilei",   "15487316252", "9809/SSP", "9781-5555", "Rua Noventa e Tres, S/N" ) );
    cadastro_incluir( &c, cadastro_criar(  60, "Ada Lovelace",      "13747920632", "1212/SSP", "9871-4532", "Rua dos Moradores, no. 100" ) );
    cadastro_incluir( &c, cadastro_criar(  70, "Marie Curie",       "41325527300", "4545/SSP", "3456-1234", "Avenida da Cidade, Nem. 32" ) );
    cadastro_incluir( &c, cadastro_criar(  80, "Nikola Tesla",      "12312312300", "6565/SSP", "8765-3456", "Rua Sem Nome, S/N" ) );
    cadastro_incluir( &c, cadastro_criar(  90, "Michael Faraday",   "99988877700", "4444/SSP", "2323-3214", "Vila da Travessa, 123" ) );
    cadastro_incluir( &c, cadastro_criar( 100, "Johannes Kepler",   "32132132111", "4343/SSP", "9898-4545", "Avenida Vazia, Numero 0" ) );

    /* Lista itens cadastrados (antes das exclusoes) */
    cadastro_listar( c );

    /* Exclui itens do cadastro */
    cadastro_remover( &c, 60 );
    cadastro_remover( &c, 70 );

    /* Lista itens cadastrados (apos exclusoes) */
    cadastro_listar( c );

    /* Libera memoria ocupada pelo cadastro */
    cadastro_destruir( c );

    return 0;
}

/* fim-de-arquivo */

I hope it helps!

    
11.05.2016 / 00:25