Return string in C for manipulation outside the function in which it was declared

Asked

Viewed 5,533 times

2

I must develop a calculator that reads strings in the algebraic form of the complex number operation. I need to manipulate the "main" vector outside the function in which it was declared (receives). How to proceed? Should pointers be used? How to use them?

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

int tam_max = 256;

int recebe(){

    int i = 0;
    int erro = 0;
    char principal[tam_max];
    char real1[tam_max];

    setbuf(stdin, NULL);
    fgets(principal, tam_max, stdin);

    for (i = 0; i < strlen(principal); i++){

        if (principal[0] == '\n'){
            erro++;
        } else if ( principal[i] == '+' || principal[i] == '-' ||
            principal[i] == '*' || principal[i] == '/' ||
            principal[i] == '=' || principal[i] == '^' ||
            principal[i] == 'i' || principal[i] == 'p' ||
            principal[i] == '0' || principal[i] == '1' ||
            principal[i] == '2' || principal[i] == '3' || 
            principal[i] == '4' || principal[i] == '5' || 
            principal[i] == '6' || principal[i] == '7' ||
            principal[i] == '8' || principal[i] == '9' || principal[i] == '\n'){
            erro == 0;
        } else {
            erro++;
        }
    } 
    return erro;
}

int validaDados(){

    int verifica = 0;
    verifica = recebe();

    if (verifica > 0){
        printf("\nCaracteres invalidos inseridos. Por favor, tente novamente.\n\n");
        validaDados();
    }

    if (verifica == 0){
        divide();
    }
}

int divide(){
    printf("OK ate aqui\n");
}

int main(){

    validaDados();

}
  • 1

    Want to return what? Will use this return as? The code does not indicate what you want and there is no description in the question of what should be done. Need to give details.

  • @bigown I need to return the "main" vector to manipulate it outside the scope in which it was declared (receives()). Later this vector will be modified within another function. My difficulty is manipulating strings of each scope without declaring them globally.

2 answers

2


The correct is to always allocate the necessary memory where you need it and pass this address to anyone who will manipulate it. In exercises the allocation of a array in the stack it’s not usually a problem. In more complex applications you may want to make dynamic allocation in heap.

The question does not clearly state how it will use so I will try something here creating and using the string in validaDados() and pass it as argument (as is passed like a pointer everything that is changed in it will be reflected in the original variable passed as argument.:

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

#define tam_max 256

int recebe(char principal[tam_max]) {
    int erro = 0;
    setbuf(stdin, NULL);
    fgets(principal, tam_max, stdin);
    for (int i = 0; i < strlen(principal); i++) {
        if (principal[0] == '\n') {
            erro++;
        } else if ( principal[i] == '+' || principal[i] == '-' ||
            principal[i] == '*' || principal[i] == '/' ||
            principal[i] == '=' || principal[i] == '^' ||
            principal[i] == 'i' || principal[i] == 'p' ||
            principal[i] == '0' || principal[i] == '1' ||
            principal[i] == '2' || principal[i] == '3' || 
            principal[i] == '4' || principal[i] == '5' || 
            principal[i] == '6' || principal[i] == '7' ||
            principal[i] == '8' || principal[i] == '9' || principal[i] == '\n') {
            erro = 0;
        } else {
            erro++;
        }
    } 
    return erro;
}

void divide() {
    printf("OK ate aqui\n");
}

void validaDados() {
    int verifica = 0;
    char principal[tam_max];
    verifica = recebe(principal);
    printf("%s\n", principal);
    if (verifica > 0) {
        printf("\nCaracteres invalidos inseridos. Por favor, tente novamente.\n\n");
        validaDados();
    }
    if (verifica == 0) {
        divide();
    }
}

int main() {
    validaDados();
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I got myself into some other trouble. But I left other things that could get better. I do not know if the code does what you want, but there is the solution requested in the question.

1

Here are some options for your case:

Option 1 - The client allocates a buffer and passes its pointer as parameter to be filled in internally by the function:

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

#define MAXBUF  (100)

char * obter_msg( char * msg, size_t tam )
{
    strncpy( msg, "Ola Mundo!", tam );
    return msg;
}

int main( void )
{
    char msg[ MAXBUF + 1 ] = {0};
    obter_msg( msg, MAXBUF );
    printf("%s\n", msg );
    return 0;
}

/* OU... */

int main( void )
{
    char * msg = (char*) malloc( (MAXBUF + 1) * sizeof(char) );
    obter_msg( msg, MAXBUF );
    printf("%s\n", msg );
    free(msg);
    return 0;
}

Option 2 - The function has an internal static buffer and always returns its pointer to the client:

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

#define MAXBUF  (100)


char * obter_msg( void )
{
    static char msg[ MAXBUF + 1 ] = {0};
    strncpy( msg, "Olah Mundo!", MAXBUF );
    return msg;
}

int main( void )
{
    printf("%s\n", obter_msg() );
    return 0;
}

Option 3 - The function dynamically allocates a buffer and returns its pointer to the client (which in turn releases the buffer after use):

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

#define MAXBUF  (100)

char * obter_msg( void )
{
    char * msg = (char*) malloc( (MAXBUF + 1) * sizeof(char) );
    strncpy( msg, "Olah Mundo!", MAXBUF );
    return msg;
}

int main( void)
{
    char * msg = obter_msg();
    printf("%s\n", msg );
    free(msg);
    return 0;
}

I hope I’ve helped!

Browser other questions tagged

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