How to equate a vector coming from a matrix with a matrix in the main function?

Asked

Viewed 564 times

1

I need to match a matrix that is returning from a function to a matrix in the main function. My goal with this is to be able to pass this same matrix as parameter to other functions without calling the function when sending the matrix.

Example:

// função para retirar os espaços digitados
int retira_espaco(int tamanho, char vetor[], int t, char retorno []){ 
    int i = 0;
    int contador = 0;
    for (i=0; i<tamanho && vetor[i] != 0; i++){ //Nesse 'for' tem que se verificar se  vetor[i] !=0 pois o fgets sempre adiciona um 0 binario no final do que foi digitado
        if (isdigit(vetor[i]) || vetor[i] == 'i' || vetor[i] == 'p'
       || vetor[i] == '+' || vetor[i] == '-' || vetor[i] == '*'
       || vetor[i] == '/' || vetor[i] == '^' || vetor[i] == '='){
            retorno[contador++] = vetor[i];
        }
    }
    retorno[contador] = '\0';
    return (retorno);
}

When sending the parameters to that first function I have to do as follows:

int main(){    
    printf("%s\n", retira_espaco(tamanho, vetor, tamanho, retorno));
}

I then want to equal a matrix in the main function the matrix that returns from the remove_space, how to proceed?

  • 2

    Hello. Welcome to SOPT. If you haven’t done it yet, do the [tour] and read [Ask]. I don’t understand your question. What does it mean to "match an array"? Match what? Nor did I understand what its function should do (the return of an integer value with the index of where supposedly there is a + or a -, which is not a matrix, has nothing to do with what the function name says it does).

  • Sorry, friend, I inserted a different function and had not realized, now I fixed. What I want to match is the return matrix with a matrix in the main function. Normally to equalize matrices you use for ( i = 0; i<10; i++){ matrix[i] = return[i]; } only that as I do not know how to do this when the return matrix, as in the case, is coming from a function.

  • I withdrew the vote to close. But still, it’s not totally clear. You want to compare the content of retorno, after the call from retira_espaco, with some other matrix, is that it? This example you posted does not compare, but rather assigns. The = unique is different from the == double comparison.

  • Exactly, because then I can use the return matrix within the main function without having to call it all the time.

  • @Miguel Goffredo, what you want I’ve already understood. Basically, it wants to change the matrix (vector by having size 1 in one of the dimensions) that passed to the function. You want the matrix you passed changed to have the new content returned. I edited your question to improve the text, make it look more inviting, fix errors and add "tags" that will be relevant. I am already to respond to you.

  • @Joseph did not edit anything ;)

  • @Jorgeb. I edited but as there are two people with editing awaiting approval of the same content (you, in case), what I edited was lost.

  • @But Jose has to be on the record anyway, and I don’t see anything. Strange...

  • @Jorgeb. It’s true; it’s not in the history! And I had edited the answer to facilitate understanding! But basically the colleague wants to change the original matrix with what was done in the function.

Show 4 more comments

2 answers

2


What you want to do is assign the array retorno which has been filled by the function retira_espaco to another array, but this is unnecessary, because arrays are passed by "reference" when they are used as function parameters. That is, the array retorno within the function retira_espaco is the same array outside the function that was passed as parameter.

Exemplifying

char x[100], y[100];

// ...outros comandos

// o array "retorno" dentro de retira_espaco na verdade e' o array y aqui de fora
retira_espaco(100, x, 100, y);

printf("%s", y);

Now, your function retira_espaco is erroneously stated as int retira_espaco, should be void retira_espaco. Also you are not using the 3rd parameter t, and that final command return (retorno) is unnecessary and actually wrong, it would only make sense if the kind of function was char *.

In addition, his example printf("%s\n", retira_espaco(tamanho, vetor, tamanho, retorno));is wrong because the format %s is for strings (char*), and you declared the function retira_espaco as int.

2

Let’s see...

The best way to deal with your problem is to use the idea of reference passage of the arguments. And that falls into that black cloud of pointers - but that’s easy after it dominates!

If you want to read about pointers, I point out this material from USP. It is short, concise and easy to understand. I also point out this question Stack Overflow in English if you master the language.

Solving the problem

Taking as truth the code you provided and letting it dry for the purpose of exemplification, what could be done is the following:

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

void retira_espaco( char * vetor ){

  int i, j, tamanho;

  tamanho = strlen( vetor );

  for ( i = 0; ( i < tamanho ) && ( vetor[i] != 0 ); i++ ){

    if( isdigit( vetor[i] ) || vetor[i] == 'i' || vetor[i] == 'p' || vetor[i] == '+' || vetor[i] == '-' || vetor[i] == '*' || vetor[i] == '/' || vetor[i] == '^' || vetor[i] == '=') {

      /* Movimenta para posteriores posições para dentro, eliminando caracteres desejados */
      for( j = i; j < (tamanho - 1); j++ ) vetor[j] = vetor[j+1];
      vetor[ tamanho - 1 ] = '\0';

      /* Por conta do movimento acima, precisa-se checar a posição atual novamente */
      --i;

    }

  }

}

int main( void ){

  char vetor[] = "abcdef+=efghijklmnopq/xyz";

  retira_espaco( vetor );

  printf( "Resultado: %s\n", vetor );

  return( 0 );

}

The result obtained is satisfactory:

Resultado: abcdefefghjklmnoqxyz

Explaining

If you create a pointer - I imagine you know what a pointer is or have read the recommended article - as a parameter to the function (example: char * vetor), you can pass your matrix vetor as a reference to the function - that is, do not pass the value but the memory address of the function. This means you can modify the contents of the original matrix.

What has been done here is simple:

  • created the function that modifies the matrix: void retira_espaco( char * vetor ){...}

  • passed, by reference, a predetermined matrix to be modified: retira_espaco( vetor );

  • whether the change has occurred: printf( "Resultado: %s\n", vetor );

Note that vectors pass by default reference. If it were an allocated vector, we would use the operator & for reference. Example:

  • the function would be: void retira_espaco( char ** vetor ){...}
  • the matrix declaration in main() would be: char **vetor = malloc(...);
  • the reference passage would be: retira_espaco( &vetor );

In this way, one could not only keep the values as well as modify the allocated memory size. With dynamic memory allocation, instead of filling with ' 0', one would get an array of appropriate size and lower memory consumption. However, it is a little more laborious and escapes the scope of presentation of the theme.

Browser other questions tagged

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