Your progress is good, but you made a couple of mistakes which I'll talk about.
1) I renamed the function to
str_cat() to avoid confusion with C++'s ready-made
std::strcat() -- which in turn becomes
strcat() because of your
using namespace std;
directive.
2) char xrray [80]
I'm pretty sure that's not enough space, and after having changed it to
char xrray[500]
it seems to work.
3) Why use
pxrray
and
pbrray
? Arrays decay to pointers. That's why you can assign an array to a pointer in the first place. This means: you can just pass directly the arrays:
str_cat(xrray, brray);
4) The
str_cat() function itself isn't correct. In the second loop, you must assign the current value of
*src
to
*dest
, then increase both.
If point
4) is confusing, think of it like this:
dest and
src are basically local variables in the
str_cat() function, and their original values are the memory addresses of the first elements in the arrays
xrray and
brray.
If you add to a pointer, you change its content (its content being a memory address, which is a number). Only when you use the dereference operation (asterisk
*) will you go to that memory address and change what's stored there.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <cstddef>
#include <iostream>
int main()
{
int ia[] = {0, 1, 2, 3, 4, 5}; // int array
int *pi = ia; // pointer to int
pi += 3;
*pi = 777;
for (std::size_t i=0; i < sizeof ia / sizeof *ia; ++i)
std::clog << "ia[" << i << "] == " << ia[i] << '\n';
}
|
ia[0] == 0
ia[1] == 1
ia[2] == 2
ia[3] == 777
ia[4] == 4
ia[5] == 5
|
And here is the program. Please be consistent in your indentation, your original code looks spilled all over the place.
Also,
str_cat() is currently a
void function. I don't know if you need to change that or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdlib>
using namespace std;
void str_cat(char *dest, char *src)
{
while (*dest != '\0')
++dest;
while (*src != '\0')
{
*dest = *src;
++dest;
++src;
}
}
int main()
{
char xrray[500] = "To be or not to be, that is the question... .";
char brray[] = "Tomorrow and tomorrow creeps in this petty place... .";
cout << "1st xrray reads: \n " << xrray << endl << endl;
cout << "2nd xrray reads: \n " << brray << endl << endl;
// there's no need for these pointers
//char* pxrray = xrray;
//char const* pbrray = brray;
cout << "\n The 'strcat' function will concatenate the two strings and display it here:" << endl;
str_cat(xrray, brray);
cout << xrray << endl;
system("pause");
return 0;
}
|
Edit: I noticed there's a bug in my version of
str_cat().
*dest = '\0';
should be added after the second loop.
This is to ensure that
dest will be NUL-terminated.