There are several problems in your code.
First, when you define a literal string with char s[] = "World";
you are allocating only the memory space required for that specific number of characters.
Since you want to join two strings, the size will increase, so you need more space. This is solved for example by setting a maximum size with char s[100] = "World";
.
Also you can’t modify a literal string, so you can’t do the function the way you did and expect it to work with strins(s, "Hello");
since he won’t be able to modify the literal string "Hello"
.
Finally, the result of the function strcat
is saved in the first parameter, so it would be saved in the orig
instead of dest
as desired. A strcpy
will suffice, though will leave the source variable "dirty", what I don’t know if it’s a problem.
Follow the code with the corrected suggested problems:
#include <stdio.h>
#include <string.h>
char *strins(char *dest, char *orig)
{
strcat(orig,dest);
strcpy(dest,orig);
return dest;
}
int main()
{
char s[100] = "World";
char outro[100]= "Hello";
strins(s,outro);
printf("%s\n",s);
return 0;
}
That returns the result:
HelloWorld
Not string inversion. String inversion is transforming
"roma"
in"amor"
. What you want is to concatenate strings and return to a specific point– Jefferson Quesado
What’s the problem with your code? What’s going on?
– Jefferson Quesado
char s[] = "World"
, what will be the size ofs
? Will there be room for you to add another text to it? The functionstrcat
wait as parameter two pointers tochar
. The order of the arguments ofstrcat
isdestination
andsource
, what you went throughorig
anddest
in this order?– Woss
The code does not display the string even if it is s[20], for example.
– rand
The intention is for the argument to stay ahead
– rand
So which way out?
– Jefferson Quesado
Returns only one value: "Process returned -1073741819 (0xC0000005)"
– rand