-3

I'm trying to copy an specific word from a C array and put it into another c array so then later I can show the output, however when I execute the program the first function call works, (I get sprightful in the output/terminal) "Copy \"sprightful\", should see \"sprightful\".\n"; however, when I call the function again it gives me this result (output/terminal) superhtful instead of super (since I specified in the argument, that I want to copy the first five characters). what's wrong?

#include <iostream>
#include <cstring>
#include <cctype>
#include <stdio.h>
#include <string.h>
#include <algorithm> 

using std::cin;
using std::cout;
using std::endl;

// function declarations
char* copy(char* destination, const char* source, size_t num);


int main()
   {
   const int WORDSIZE = 15;
   char words[][WORDSIZE] = {"sprightful", "reason to row", "New York", "Bolton", "Frida", ""};
   char word[WORDSIZE];



   copy(word, words[0], sizeof(word) - 1);
   cout << word << endl << endl;



   copy(word, "Supercalifragilisticexpialidocious", 5);
   cout << word << endl << endl;

   return 0;
    }


char* copy(char* destination, const char* source, size_t num)
 {
    strncpy(destination, source, num); 
    return destination;
 }
  • Possible duplicate of [Why does strncpy not null terminate?](https://stackoverflow.com/questions/1453876/why-does-strncpy-not-null-terminate) – Kevin Feb 08 '19 at 03:10

2 Answers2

1

You aren't clearing word in between the two function calls. On the second call it only overwrites the first 5 characters ("super"), and the rest is the result of your previous call.

Brandon Lyons
  • 473
  • 3
  • 10
0

@Brandon is correct. Try clearing word between your function calls:

    int main()
    {
    const int WORDSIZE = 15;
    char words[][WORDSIZE] = { "sprightful", "reason to row", "New York", "Bolton", "Frida", "" };
    char word[WORDSIZE];


    // Test the copy function
    std::cout << "Copy \"sprightful\", should see \"sprightful\".\n";
    copy(word, words[0], sizeof(word) - 1);
    cout << word << endl << endl;

    memset(&word[0], 0, sizeof(word)); //Clear the char array.

    // Test the limit on the copy function
    cout << "Copy \"Supercalifragilisticexpialidocious\", should see \"Super\".\n";
    copy(word, "Supercalifragilisticexpialidocious", 5);
    cout << word << endl << endl;

    getchar();
    return 0;
}
AdaRaider
  • 1,126
  • 9
  • 20