Question

I'm kind of just starting in C++ so I might have a dumb mistake here. Below is my code along with outputs in the comments. I'm using Xcode.

#include <iostream>
#include <string.h>

using namespace std;

 int main() {

          char myString[] = "Hello There";
          printf("%s\n", myString);

         strncpy(myString, "Over", 5); // I want this to print out "Over There"

         cout<< myString<<endl; // this prints out ONLY as "Over"

         for (int i = 0; i <11; i++){
         cout<< myString[i];
          }// I wanted to see what's going on this prints out as Over? There
          // the ? is upside down, it got added in

         cout<< endl;
         return 0;
}
Was it helpful?

Solution

THE PROBLEM

  • strncpy (destination, source, max_len)

strncpy is defined to copy at most max_len characters from source to destination, including the trailing null-byte if source doesn't include a null-byte within the first max_len bytes.

In your case the trailing null-byte will be including, and with that destination will be null-terminated directly after "Over", which is why you are seeing the described behaviour.

After your call to strncpy myString will therefore compare equal to:

"Over\0There"

THE SOLUTION

The most straight-forward solution would be to not copy the trailing null-byte from "Over", which is as easy as specifying 4 instead of 5 to strncpy:

strncpy(myString, "Over", 4);

OTHER TIPS

The documentation for strncopy is as follows:

char * strncpy ( char * destination, const char * source, size_t num );

Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

By calling strncpy(myString, "Over", 5), you are actually copying "Over\n" into myString. You are probably better off calling strncpy with the last parameter as strlen(source).

Try the following

#include <iostream>
#include <string.h>

using namespace std;

 int main() {

   char myString[] = "Hello There";
   printf("%s\n", myString);

   strncpy(myString, "Over", 4); // I want this to print out "Over There"
   strcpy( myString + 4, myString + 5 ); 

   cout<< myString<<endl; // this prints out ONLY as "Over"

   for (int i = 0; i <10; i++){
    cout<< myString[i];
   }// I wanted to see what's going on this prints out as Over? There
    // the ? is upside down, it got added in

   cout<< endl;

   return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top