0

Here is what I want:
Declare a character array of size 15 to store character (string input) value from the user. Now perform the following tasks:

  • Pass the array to function copy().
  • Define another array of the same size in above function. Copy the values of the first array to the second array and display on the console.
  • From function Copy() pass both arrays to function compare(). At that function compare both arrays and display message "Equal" if the condition is fulfilled.

Here is my code

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;

void mycopy(char array);
int main(){
//Using Loop to input an Array from user

char array[15];
int i;
cout << "Please Enter your 15 characters" << endl;
cout << "**************************************************" << endl;
for (i = 0; i < 15; i++)
{
    cin >> array[i];
}

// output each array element's value
cout << "Please Enter your 15 characters" << endl;
cout << "**************************************************" << endl;
cout << "Element" << setw(13) << "Value" << endl;
for (int j = 0; j < 15; j++) {
    cout << setw(7) << j << setw(13) << array[j] << endl;
}

mycopy(array[15]);

return 0;
}

void mycopy(char array[15]) {

char array1[15];
strncpy_s(array1, array, 15);
cout << "The output of the copied Array" << endl;
cout << "**************************************************" << endl;
cout << "Element" << setw(13) << "Value" << endl;
for (int j = 0; j < 15; j++) {
    cout << setw(7) << j << setw(13) << array1[j] << endl;
}

}

The above code is to pass the array to function Copy() and copy the values of the 1st array to the 2nd char array but the code generates an exception due to the invalid parameter is passed. As I have searched the stack overflow but I didn't find any similar question that could solve my problem. Thanks in advance.

Sangeen Khan
  • 175
  • 1
  • 20

1 Answers1

1

Do not use strncpy_s, it is non-standard. Instead, use strncpy as you were originally. In order to use it, you need to include cstring.

#include <cstring>

Your prototype and definition for mycopy() are different. Your prototype takes a char but your definition takes a char array. Make them both take an array. Either of the following three will work the same:

void mycopy(char* array);
void mycopy(char array[]);
void mycopy(char array[15]);

When you are calling mycopy() in main() you are attempting to access the array at the 15th index and pass that character to the function. This is wrong because the 15th index is out of bounds and because the function takes a pointer to a char array, not a char. You need to just pass the pointer to the array.

mycopy(array);
bgfvdu3w
  • 1,548
  • 1
  • 12
  • 17