Store words in a "char" vector

Asked

Viewed 44 times

-1

I’m trying to make an algorithm that returns the region of the CPF that was informed, but I’m bumping into the character limit that a variable of the type char allows in C language.

I tried to perform the procedure in two ways, but I could not identify my mistake in any of them.

Through a Matrix:

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

void origem(int a[10])
{
    int i;
    char regioes[9][60] = {
        'Rio Grande do Sul',
        'Regiao Centro-Oeste',
        'Regiao Norte',
        'Ceara, Maranhao e Piaui',
        'Paraiba, Pernambuco, Alagoas e Rio Grande do Norte',
        'Bahia e Sergipe',
        'Minas Gerais',
        'Rio de Janeiro e Espirito Santo',
        'Sao Paulo',
        'Parana e Santa Catarina'};

    printf("\nOrigem do CPF: ");

    for (i = 0; regioes[a[8]][i] != NULL; i++)
    {
        printf("%s", regioes[a[8]][i]);
    }
}

int main(){
                
    int cpf[10] = {5, 2, 9, 9, 8, 2, 2, 4, 4, 2, 5}; 
    origem(cpf);

return 0;
}

 

And through the function malloc:

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <locale.h>

void origem(int a[10])
{
    int i;
    char regioes[9];

    for (i = 0; i <= 9; i++)
    {
        regioes[i] = malloc(60); //aloca espaço uma string de 59 carateres
    }

    regioes[0] = 'Rio Grande do Sul';
    regioes[1] = 'Centro-Oeste';
    regioes[2] = 'Norte';
    regioes[3] = 'Ceará, Maranhão e Piauí';
    regioes[4] = 'Paraíba, Pernambuco, Alagoas e Rio Grande do Norte';
    regioes[5] = 'Bahia e Sergipe';
    regioes[6] = 'Minas Gerais';
    regioes[7] = 'Rio de Janeiro e Espírito Santo';
    regioes[8] = 'São Paulo';
    regioes[9] = 'Paraná e Santa Catarina';

    printf("\nOrigem do CPF: %s", regioes[a[8]]);
}

int main()
{
    int cpf[10] = {4, 4, 5, 6, 8, 5, 6, 0, 8, 4, 5};
    origem(cpf);

    return 0;
}

A execução fica da seguinte forma

2 answers

0

You initialized very small arrays for both Cpf, and both the regions, so to solve the reported problem just add more at each startup, as in the code below.

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

void origem(int cpf[10])
{
    char regioes[10][60] = {
        "Rio Grande do Sul",
        "Regiao Centro-Oeste",
        "Regiao Norte",
        "Ceara, Maranhao e Piaui",
        "Paraiba, Pernambuco, Alagoas e Rio Grande do Norte",
        "Bahia e Sergipe",
        "Minas Gerais",
        "Rio de Janeiro e Espirito Santo",
        "Sao Paulo",
        "Parana e Santa Catarina"
    };

    printf("\nOrigem do CPF: ");

    // Não sei o que esse código deveria fazer, mas aqui tem um erro de comparação
    for (int i = 0; regioes[cpf[8]][i] != NULL; i++)
    {
        printf("%s\n", regioes[cpf[8]][i]);
    }
}

int main(){
    int cpf[11] = {5, 2, 9, 9, 8, 2, 2, 4, 4, 2, 5}; 
    origem(cpf);

    return 0;
}
  • I really left room for this error of 0, thank you very much for the touch. But with this same Cpf Array I made a validation function and worked perfectly. I changed their size here, but the execution still doesn’t show the region.

  • I do not know the logic to know which region of a Cpf, just solved the problem you presented.

0


I am trying to make an algorithm that returns the region of the CPF that was informed, but I am running into the character limit that a Char variable allows in the C language

No, your problem is not in this hypothetical limit, in either case.

In C the character limit for a variable charis 1.

Case 1

Through a Matrix:

Your program has many errors. I will show some and then a possible way to write this. So you can compare and draw your conclusions.

Of your program

void origem(int a[10])

Its function receives a vector of 10 int and does not return anything. Almost certainly not what you wanted. For what will pass 10 values? Wouldn’t it be the case to pass the CPF as a string, only the value of the digit that corresponds to the region? And the CPF has 11 digits, not 10. And it won’t operate with them, so it’s simpler to use char[11].

    int  i;
    char regioes[9][60] = {
        'Rio Grande do Sul',
        'Regiao Centro-Oeste',
        'Regiao Norte',
        'Ceara, Maranhao e Piaui',
        'Paraiba, Pernambuco, Alagoas e Rio Grande do Norte',
        'Bahia e Sergipe',
        'Minas Gerais',
        'Rio de Janeiro e Espirito Santo',
        'Sao Paulo',
        'Parana e Santa Catarina'};

Never declare the control variable of a loop outside of it without a serious reason. It took about 10 years to correct that in the language, but it was done 40 years ago.

The string separator is " and not '

    for (i = 0; regioes[a[8]][i] != NULL; i++)
    {
        printf("%s", regioes[a[8]][i]);
    }

regioes[a[8]][i] is a char and not a pointer.

    int cpf[10] = {5, 2, 9, 9, 8, 2, 2, 4, 4, 2, 5};

Stated cpf as int[10] but listed 11...

An example

For simplicity imagine the declared function

const char* origem(const char*);

'Cause then you can call it anyway, for example

    printf("Testando com o CPF %s: origem \"%s\"\n",
        "52998224425", origem("52998224425"));

and see

Testando com o CPF 52998224425: origem "Paraiba, Pernambuco, Alagoas e Rio Grande do Norte"

Without declaring more variables.

Because const char* ? To make it clear that can’t change these values. The region table is static, fixed, allocated in the function. You pass the number of the CPF, which the function also cannot change, and it returns the region. is common in C.

Here’s a test

int main()
{
    char um_CPF[] = { "52998224X25"};

    printf("Testando com o CPF %s: origem \"%s\"\n",
        "52998224425", origem("52998224425"));

    // vai trocar o X
    printf("\nTestando a tabela:\n\n");
    for (int i = 0; i < 10; i += 1)
    {
        um_CPF[8] = '0' + i;
        printf(
            "\
CPF\t%s\tOrigem:\t%s\n",
            um_CPF, origem(um_CPF));
    };
    return 0;
}

Note that the table index in C is an unsigned integer, and the CPF has been declared as a char[11], more comfortable since it will not operate with the digits. So you need to convert the digit of char for int to access the table, and this is the account x - '0' to have the decimal from the char x, and '0'+ d to have the char from one decimal d.

a version of origem()

const char* origem(const char* cpf)
{
    static const char* regiao[] = 
    {
        "Rio Grande do Sul",
        "Regiao Centro-Oeste",
        "Regiao Norte",
        "Ceara, Maranhao e Piaui",
        "Paraiba, Pernambuco, Alagoas e Rio Grande do Norte",
        "Bahia e Sergipe",
        "Minas Gerais",
        "Rio de Janeiro e Espirito Santo",
        "Sao Paulo",
        "Parana e Santa Catarina"
    };
    return regiao[cpf[8]-'0'];
}

Note that you do not need to declare the table size: the compiler can count this alone. And declare as static is important because so can use in main() addresses without having to copy before returning.

the output of the example

Testando com o CPF 52998224425: origem "Paraiba, Pernambuco, Alagoas e Rio Grande do Norte"

Testando a tabela:

CPF     52998224025     Origem: Rio Grande do Sul
CPF     52998224125     Origem: Regiao Centro-Oeste
CPF     52998224225     Origem: Regiao Norte
CPF     52998224325     Origem: Ceara, Maranhao e Piaui
CPF     52998224425     Origem: Paraiba, Pernambuco, Alagoas e Rio Grande do Norte
CPF     52998224525     Origem: Bahia e Sergipe
CPF     52998224625     Origem: Minas Gerais
CPF     52998224725     Origem: Rio de Janeiro e Espirito Santo
CPF     52998224825     Origem: Sao Paulo
CPF     52998224925     Origem: Parana e Santa Catarina

Case 2

through the Malloc function:

The function is malloc()

Of your program

void origem(int a[10])

This is the same statement of the first program and I didn’t understand: a is int[10] but Cpf has 11 digits. What if you already have the vector digit by digit why didn’t you just pass the ninth digit? Something like

void origem(int digito)

And the declaration of regioes

    int  i;
    char regioes[9];

    for (i = 0; i <= 9; i++)
    {
        regioes[i] =
            malloc(60);  // aloca espaço uma string de 59 carateres
    }

regioes is a vector of char. Fixed. With 9 char. And you have 10 regions and they’re not char. Sane char* or char[], vectors.

In the for should declare i and not before, for the reason I explained at the beginning.

regioes[i] is a char. malloc() returns void*, a pointer. Can’t write that.

And not even that

    regioes[0] = 'Rio Grande do Sul';

The string delimiter is " and not '.

    printf("\nOrigem do CPF: %s", regioes[a[8]]);

And regioes[ a[8] ] is a char. Cannot use with specifier %s in the printf().

When declaring a vector, prefer the singular name, because it will access one occurrence at a time much more than the group as a whole. Then regiao[0] to regiao[9] is perhaps better as a name.

An example of this case

I can’t see a reason to use malloc() in such a case, because the values are a table of fixed values.

I will show an example using the same function origem(), but creating a string array. This is the most common thing in C since the prototype of main() is

    int    main( int argc, char** argv );

And the system mounts a string array with input parameters to ALL OVER program C.

Assembling a string vector with the regions

    char*  cpf_teste = "12345678X01";
    int    N = 10;
    char** regiao;

So the example goes:

  • vary the X there in the CPF of 0 to 9 and show the region using origem()
  • create and load the pointer array regiao with the obtained values calling clear origem()
  • erase the allocated vector

Creating the block

    int    N = 10;
    char** regiao = (char**)malloc(10 * sizeof(char*));
    for (int j = 0; j < N; j += 1)
    {
        cpf_teste[8] = '0' + j;  // converte para char
        char* uma    = (char*) origem(cpf_teste);
        regiao[j]    = (char*)malloc((1 + strlen(uma)) * sizeof(char));
        strcpy(regiao[j], uma);  // copia
    };  // for()

regiao is a pointer vector so initially an area is allocated to them. And each one is created in a loop, varying the digit of the CPF that has the region and calling origem(). As the function returns a pointer this pointer is used to see the size of the string and is then allocated a space with an extra byte to contain the 0 terminating every string in C. And a call to strcpy() copies the string to the array.

Then the vector is released via free() and the program ends.

output from example 2


Testa vetor de 10 strings:

 1  Rio Grande do Sul
 2  Regiao Centro-Oeste
 3  Regiao Norte
 4  Ceara, Maranhao e Piaui
 5  Paraiba, Pernambuco, Alagoas e Rio Grande do Norte
 6  Bahia e Sergipe
 7  Minas Gerais
 8  Rio de Janeiro e Espirito Santo
 9  Sao Paulo
10  Parana e Santa Catarina

Apaga tudo

Fim

The complete program

The function is the same.

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

const char* origem(const char* cpf)
{
    static const char* regiao[] = {
        "Rio Grande do Sul",
        "Regiao Centro-Oeste",
        "Regiao Norte",
        "Ceara, Maranhao e Piaui",
        "Paraiba, Pernambuco, Alagoas e Rio Grande do Norte",
        "Bahia e Sergipe",
        "Minas Gerais",
        "Rio de Janeiro e Espirito Santo",
        "Sao Paulo",
        "Parana e Santa Catarina"};
    return regiao[cpf[8] - '0'];
}

int main(void)
{
    char*  cpf_teste = "12345678X01";
    int    N = 10;
    char** regiao = (char**)malloc(10 * sizeof(char*));
    for (int j = 0; j < N; j += 1)
    {
        cpf_teste[8] = '0' + j;  // converte para char
        char* uma    = (char*) origem(cpf_teste);
        regiao[j]    = (char*)malloc((1 + strlen(uma)) * sizeof(char));
        strcpy(regiao[j], uma);  // copia
    };  // for()

    // agora testa
    printf("\nTesta vetor de %d strings:\n\n", N);
    for (int i = 0; i < 10; i += 1)
        printf("%2d  %s\n", 1 + i, regiao[i]);

    // agora apaga o vetor todo
    printf("\nApaga tudo\n");
    for (int i = 0; i < 10; i += 1)
        free(regiao[i]); // apaga as strings
    free(regiao); // apaga o vetor

    printf("\nFim\n");
    return 0;
}

Browser other questions tagged

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