#include <iostream>
usingnamespace std;
char *strcat(char *, constchar *);
int main()
{
char a[100];
cout << "Enter First String: ";
cin.getline(a, 100);
char b[100];
cout << "Enter Second String: ";
cin.getline(b, 100);
a = strcat(a, b);
system("pause");
return 0;
}
char *strcat(char *a, constchar *b)
{
char c[100];
int i = 0;
for (i; i < 100; i++)
{
if (a[i] == '\0')
break;
c[i] = a[i];
}
for (i; i < 100; i++)
{
if (b[i] == '\0')
break;
c[i] = b[i];
}
return c;
}
I am not quite sure if this will work fine because I am unable to test it due to one error, in the line,
a = strcat(a, b);
It is saying that it can't assign the function to "a" array... which I am unable to understand. Because my function is returning an address of character array and that address should be able to store in a as it is an array (which is a pointer itself).
So, what is it here that I am getting wrong and what should I do to fix it?
Thank you!
How do you intend to assign a pointer to an array? (All we know is that the function returns a pointer.)
You would have to explicitly copy values from one array to an another.
Test:
1 2 3 4 5 6 7
int foo[5];
int* bar = nullptr;
foo = bar; // error;
// EDIT: error for arrays too:
int gaz [42];
foo = gaz; // error
1 2
char c[100];
return c;
You have an array inside the function. It's memory will be deallocated at the end of the function.
You will return the address within stack that no longer has a valid array.
That is a fatal mistake.
The second loop:
Lets take "Hello" + "foobar".
The first loop ends because a[5] is null.
Then you test b[5]. The 'r' is not null and you copy:
c[5] = b[5]
Was your intention to skip the "fooba"? What if b had been "foo"?
If you do have two 99-char strings, how could they fit into one 99-char text (the 100th char is for null)?
char *strcat(char *a, const char *b)
{
... copy b onto the end of a here, including b's terminal zero char.
overwrite a's terminal zero as the starting point.
}
once you have that working, you can fix the return value.
(Just one slight problem, which is this that it also prints all the garbage values but that's easy to fix and will do it now... Otherwise, working perfectly!)
Thank you :)