How do I return a string from a char function? The returned value is NULL

Asked

Viewed 44 times

2

I am having problems with creating a char function that returns a string typed by the user. I call her in a registration method and try to play for the struct variable.

cadastrarLocacaoNome();
 strcpy(inserir.nomeCliente, cadastrarLocacaoNome());

I have already imprinted value returned by the function and is giving NULL, follows below the form I wrote it:

char cadastrarLocacaoNome(){
    char nomeCliente[100];
    printf ("Informe o nome do cliente\n");
    fflush (stdin);
    fgets (nomeCliente, 100, stdin);
    return nomeCliente[100];
}

1 answer

2


One string in C is a character array, an array, ending with \0. When will we manipulate a string, we use your memory address, then to return a string we need to return the memory address of the first element. In your code you are returning only one char, that is, a single character. Oberserve:

/* Essa funcao retorna um unico caractere */
char cadastrarLocacaoNome(){

To return a string we need to return the address of the first element, if we are returning a endereço, then the function should return a ponteiro. But if we need one string why do we return a ponteiro? Because a ponteiro can behave like a array. There are two questions about that: Arrays are pointers? and pointer to vector vs pointer to variable.

So your job should be like this:

/* Agora essa funcao retorna um ponteiro de char */
char* cadastrarLocacaoNome(){

Now your function returns a pointer, so we have to change that:

/* Outro problema aqui eh que a posicao 100 nao faz parte do seu vetor */
return nomeCliente[100];

To the address of the first position of your vector, thus:

return &nomeCliente[0];
/* Essa forma abaixo equivale como a primeira posicao do vetor */
return nomeCliente;

Another problem in your code is about the lifespan of char nomeCliente[100];. This vector exists only in its function, when the return, His life time is over.

When strcpy is called, it is necessary that the variable nomeCliente is still "alive". For this to happen we can declare the vector outside the function, but with this there would be no need to return a string. Another solution is to use memory allocation, where the variable will be in the heap and with it your life time can be controlled. In C we can use malloc to allocate memory and free to free the memory allocated by malloc.

So your show would look like this:

char* cadastrarLocacaoNome(void) {
    /* Alocando 100 bytes para esse ponteiro, assim podemos usa-lo
       como se fosse um vetor */
    char *nomeCliente = malloc(sizeof *nomeCliente * 100);

    /* Se o ponteiro for NULL entao houve algum erro */
    if (nomeCliente != NULL) {
        /* Aqui eh ativado caso a alocacao seja bem sucedida */
        printf("Informe o nome do cliente: ");
        fgets(nomeCliente, 100, stdin);
    }

    /* Retornando o endereco alocado que tem a string lida ou
    NULL - em case de erro */
    return nomeCliente;
}

Now just use the function return as if it were a string. One detail is that you should not do this:

strcpy(nome, cadastrarLocacaoNome());

Because the returned address (string) needs to be released with the free. Behold: What is the purpose of the free function?. So we can use an auxiliary variable, like this:

char nome[100];
/* Coloando a string no ponteiro auxiliar */
char *auxiliar = cadastrarLocacaoNome();

/* A funcao retorna NULL em caso de erro na alocacao */
if (auxiliar == NULL) {
    puts("Erro ao alocar memoria!");
    return 1;
}

/* Copiando a string */
strcpy(nome, auxiliar);

/* Liberando a memoria alocada */
free(auxiliar);

printf("Nome: %s", nome);

See the code working here

Browser other questions tagged

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