Error in string inversion

Asked

Viewed 63 times

1

I’m trying to reverse one string through a function only that it is giving error, however I do not know where it is wrong.

Right below is my code.

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

 char troca(char nome[100], char nome1[100]);

 int main(void)
{
   char nome[100];
   printf("Informe o nome para ser invertida :");
   scanf("%s", nome);
   printf("%s\n", troca(nome));
   system("pause");
   return 0;
}

char troca(char nome[100], char nome1[100])
  {
    int c = 0, i;
    for(i = strlen(nome) - 1; i >= 0; i--)
    {
      nome[c] = nome[i];
      c++;
    }
    nome1[c] = '\0';
    return nome1[c];
  }
  • Should not be name1[c] = name[i]; instead of name[c] = name[i];

  • and Return name1;

  • and should be "exchange char* (" instead of "exchange char("

  • exchange has two parameters and you are only passing 1

  • and string. h is not being used

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

Show 1 more comment

1 answer

2

There’s a lot of mistakes there:

  • Not passing the second argument, actually the parameter is not necessary
  • Not returning something useful by use
  • Not accepting spaces in data entry
  • Some errors would appear if some of these errors were fixed.

It gets better:

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

char *troca(char nome[100]) {
    for (int i = 0, j = strlen(nome) - 1; i < j; i++, j--) {
        char temp = nome[i];
        nome[i] = nome[j];
        nome[j] = temp;
    }
    return nome;
}
  
int main(void) {
   char nome[100];
   printf("Informe o nome para ser invertida :");
   scanf("%[^\n]s", nome);
   printf("%s\n", troca(nome));
}

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

Browser other questions tagged

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