Remove array element in C

Asked

Viewed 9,106 times

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 input) and I want to delete ( ie, play the Front Dice items, -1.

//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’t 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 didn’t happen the way I wanted and the program stops and goes back to the menu;

  • 1

    Give us more details, just this won’t help you.

  • Okay, imagine a sales terminal. You want to remove a customer, or even a product, vc "list" with a loop the items and in front vc (index) with the variable of the loop for, and displays all registered products, blz, ai display a message for you, want to delete any item/customer? type the input, then you will type the input, and from the typed number it starts to "move the input i+1, to the i" literally moving 1 back and overwriting that input of the vector that the user specified, my idea is this. :)

  • 2

    This is all already in the question. This is abstract. This matters little to us to help you, unless we do everything for you, which is not the purpose of the site. Ask the question concrete things you are doing, how is your code. What is your problem, etc.

  • Have you tried that: for( i = posicao; i < 10 - 1; i++) { c[ i ] = c[ i + 1 ] }; ?

  • Lacobus, it was my thought. bigown, sorry if I still can’t properly express all my need through my codes and line of thought, "for me" is still quite something, and all the code is related to what I know (I know very little thing), and what happens, is just what you commented, is not the purpose of the site, you give me the code point, even why I would not learn absolutely anything and, on the day of evaluation I will think, I had the code done not thought of anything, will not save me, I will not have the site to ask in the test.

2 answers

2

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

Imagine 10 coins lined up on the table. You remove one of them and move the others to her place. You don’t 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 of the one that came out and will be placed in the position of the one that came out, the next for this place, etc.

Then you have to have a variable with the position of the element to be removed. Have an instruction to get a user input and put it in a variable. Find out which one is.

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

See if this description helps you.

Edition responding to the author’s comment

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

  • you can create a new smaller array and copy everything there. More or less thus:

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 pq you have to adapt this to what decreases the array.

  • or vc can simply work with the array without decreasing to each element and just delete the array at the end.

If you choose the 2nd option of course some space in memory will be allocated without use. But no memory Leak occurs. Just a waste of a few bytes. So in your case this space is derisory and this kind of preciousness takes up too much of your time (expensive time for a company). So worry about optimizing on that 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 talents of optimization and control of Leaks :)

  • Basically this is my idea, I already ask the user, which position he wants to start, I say in the vector, for him to start from that position on, and then he’s always going back -1, in case I worry "I don’t know if you need" with the last position will be empty or memory junk

1

Follow the complete solution of customer registration 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 chained list instead of using a static vector.

Follow 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!

  • Hey, Lacobus, what’s up? then I have not learned list, malemal we learn stack, but thank you very much for your help with the code, it is more even an idea of vectorization, where I point the vector Inux, and bring the front element in place of what was excluded.

  • @Marciohenrique Pronto! I edited the answer and includes a solution using a static vector.

  • Wow Lacobus, that code mass to reading, for the little bit of Exp I have in progress, and seeing its form of programming, to :-o

Browser other questions tagged

You are not signed in. Login or sign up in order to post.