0

I'm learning pointers in C++, while not as clear as I'd like to be on the subject, I'm slowly getting there.

My goal here was to write a function using pointer notation, to go through an array and change the case of the input.

For example

("ab7d") myToUpper() -> AB7D

Here is my idea for accomplishing this.

void myToUpperCase(const char *source, char *dest)
{
    for (int i = 0; *(source + i) != '\0'; i++)
    {
        *(dest + i) = toupper(* (source + i));
    }
}

Results

("ab7d") myToUpper() -> AB7D\377

Would someone mind explaining the reasoning behind \377 being added to the output, obviously I'm looking for just the source to be changed here with nothing else added to the output.

Thanks

5
  • You're not null-terminating your output. Commented May 15, 2016 at 21:40
  • @KerrekSB would you mind explaining? I'm fairly new to C++. Commented May 15, 2016 at 21:41
  • 1
    Turn the for loop into a do-while loop.. Commented May 15, 2016 at 21:42
  • why not using iterators and better..why not for_each and lambaded toupper? Commented May 15, 2016 at 21:45
  • Also beware of potential toupper UB. stackoverflow.com/questions/21805674/… Commented May 15, 2016 at 21:45

1 Answer 1

1

Strings are char arrays with a '\0' byte as a terminating character.

Your code is copying anything but the final '\0' byte. So, if you chnage your code to terminate dest with a \0' byte all will be fine. (The '\377' you are observing just is the byte that happens to occur at that position in dest.)

eg. you could change your code to:

void myToUpperCase(const char *source, char *dest)
{
    for (int i = 0; ; i++)
    {
        if (*(source + i) == '\\0') 
        {
            *(dest + i) = *(source + i);
            break;
        }
        else
        {
            *(dest + i) = toupper(* (source + i));
    }
}

You might also try another solution without any index i based on :

while(*source++ = *dest++) /* empty body */;

(Purists (validly) might flag using side effects within loop conditions as bad smell! But it just should give an idea....)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.