23k
23k

Reputation: 1399

Looping through an array with pointer notation

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

Upvotes: 0

Views: 397

Answers (1)

rpy
rpy

Reputation: 4023

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....)

Upvotes: 1

Related Questions