Add a char on a char pointer in C/C++

Asked

Viewed 171 times

-1

I need to add a char on a pointer of char. For example: I have a pointer of char called name, which receives "log", after the process, I want it to be "log1".

I tried to implement it like this, but it didn’t work.

 bool trocarNome(char *nome){
     nome +='1';
     cout<<nome;
  }
  • 1

    Is there a reason not to use the class string?

2 answers

3

Julio’s answer works and is technically correct. But the code is written in C++. And the recommended in this language is to use the type string whenever possible. If there is no reason to avoid it, it would be better to do so:

bool trocarNome(string nome) {
    nome += '1';
    cout << nome;
    return true;
}

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

3


In C, you can use the strncat function, it would look like this:

#include <string.h>
...
bool trocarNome(char *nome){
    strncat(nome, "1", 1);
}
  • I’m using strncat(name, "1", 1); because the way you wrote was giving syntax error, but now enters an infinite loop and badges the program.

  • Yes, sorry, I copied your code and forgot q strncat gets a string, not char. About the error, it’s hard to say, it depends on how the rest of your code is doing, but you can check if the "name" pointer still has space allocated for more characters.

  • I reinforce the comment of @Jjoao that should correct the '1' in your solution. You get my +1 only after doing it. :)

  • 1

    In fact, it is so critical, that I left a "-1" here - only strncat, no room for more characters will not work,

  • Corrected the solution ;-)

  • Okay, thanks for correcting. You got my +1 as promised. I take this opportunity to warn @jsbueno (who knows he takes his -1 after the fix?). :)

  • 1

    Ah - no - swapping 'for " is practically a typo - the biggest problem is having no comment - nor code dealing with the situation - of not having room for a larger string with the use of strncat.

Show 2 more comments

Browser other questions tagged

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