Need advice (hint) or help create 2 string function - c

The function receives two strings str1 and str2 and returns an integer. The function will insert the str2 string at the beginning of the str1 string. When the str1 string size will not change. If the length of the str1 string can contain the entire str2 string, the function will change str1 to contain str2 and then The letters of str1 up to the original length of str1. In this case the function will return 1. If the str2 string is longer than str1, the first letters of str2 will be placed in the str1 string up to str1, In this case the function will return 0.
Example 1:
str1 = "abcdefgh" str2 = "xyz"
After running the function:
str1 = "xyzabcde"
And the function will return 1.
Example 2:
str1 = "abcd" str2 = "efghj"
After running the function:
str1 = "efgh"
And the function will return 0
I started this one
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int string_pre(char *str1, char *str2) {
int sizeStr1 = strlen(str1);
int sizeStr2 = strlen(str2);
}
int main() {
char str1[]= "abcdefgh";
char str2[]= "xyz";
string_pre(str1, str2);
printf("After concatenation: %s %s \n", str1, str2);
printf("After concatenation: %s \n", str2);
return 0;
}
Not sure if this is the correct way to start.

You have a good start. You might use size_t instead of int for the string lengths and define str2 as const char *str2 as it is not modified in the function so you can accept constant strings for this argument. Next should come a test if the length of str1 is greater or equal to the length of str2 and appropriate action should be taken in both cases.
Note that your main function should test multiple cases and print the return value too.
Here is a modified version:
#include <stdio.h>
#include <string.h>
int string_pre(char *str1, const char *str2) {
if (*str2 == '\0') { // quick test for trivial case
return 1;
} else {
size_t sizeStr1 = strlen(str1);
size_t sizeStr2 = strlen(str2);
if (sizeStr1 >= sizeStr2) {
memmove(str1 + sizeStr2, str1, sizeStr1 - sizeStr2);
memcpy(str1, str2, sizeStr2);
return 1;
} else {
memcpy(str1, str2, sizeStr1);
return 0;
}
}
}
int main() {
char str1[]= "abcdefgh";
char str2[]= "xyz";
char str3[]= "xyzxyzxyzxyz";
char str4[]= "ABCDEFGH";
int n1 = string_pre(str1, str2);
printf("test1: n1=%d str1='%s' str2='%s'\n", n1, str1, str2);
int n2 = string_pre(str1, str3);
printf("test2: n2=%d str1='%s' str3='%s'\n", n2, str1, str3);
int n3 = string_pre(str1, str4);
printf("test3: n3=%d str1='%s' str4='%s'\n", n3, str1, str4);
return 0;
}
Output:
test1: n1=1 str1='xyzabcde' str2='xyz'
test2: n2=0 str1='xyzxyzxy' str3='xyzxyzxyzxyz'
test3: n3=1 str1='ABCDEFGH' str4='ABCDEFGH'

This should do the work.
however - using strlen to determine the length of a string buffer is normally a bad practice, as you may use buffers that are larger than the actual string they store. a more c way would be to pass on the length of buffer available.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int string_pre(char *str1,char *str2)
{
size_t sizeStr1 = strlen(str1);
size_t sizeStr2 = strlen(str2);
long chars_to_move_right = sizeStr1 - sizeStr2;
size_t chars_to_copy = sizeStr2 > sizeStr1 ? sizeStr1 : sizeStr2;
// have to use memmove since the copying may overlap
if (chars_to_move_right > 0)
{
memmove(str1 + sizeStr2, str1, chars_to_move_right);
}
// no overlap expected here, and memcpy may be more efficient.
memcpy(str1, str2, chars_to_copy);
return sizeStr1 >= sizeStr2;
}
int main()
{
char str1[]= "abcdefgh";
char str2[]= "xyz";
printf("Before concatenation: '%s' '%s' \n",str1,str2);
int res = string_pre(str1,str2);
printf("After concatenation: '%s' '%s' \n",str1,str2);
printf("Result = %d\n", res);
return 0;
}

Not sure if this is the correct way to start.
For starters neither declaration from the header <stdlib.h> is used in your program. So you may remove it.
The second function parameter must be declared with qualifier const because the corresponding string is not changed within the function.
int string_pre(char *str1, const char *str2);
The return type of the function strlen is size_t. So the variables sizeStr1 and sizeStr2 must be declared as having the type size_t.
size_t sizeStr1 = strlen(str1);
size_t sizeStr2 = strlen(str2);
Now all is ready to fill the body of the function with a code as for example :)
#include <stdio.h>
#include <string.h>
int string_pre( char *s1, const char *s2 )
{
size_t n1 = strlen( s1 );
size_t n2 = strlen( s2 );
int moved_right = n2 < n1;
if ( moved_right )
{
memmove( s1 + n2, s1, n1 - n2 );
}
else
{
n2 = n1;
}
memcpy( s1, s2, n2 );
return moved_right;
}
int main( void )
{
char s1[] = "abcdefgh";
char s2[] = "xyz";
int result = string_pre( s1, s2 );
printf( "%d: %s\n", result, s1 );
char s3[] = "abcd";
char s4[] = "efghj";
result = string_pre( s3, s4 );
printf( "%d: %s\n", result, s3 );
}
The program output is
1: xyzabcde
0: efgh
If in case when the both strings are equal each other and you need to return 1 then in this case change this line
int moved_right = n2 < n1;
for example to this line
int moved_right = !( n1 < n2 );
Strictly speaking the function should be declared like
int string_pre(char * restrict str1, const char * restrict str2);

Rather than run the maximum length of both strings, how about iterating no more than the length of the first string?
int replace(char *str1, const char *str2) {
size_t len1 = strlen(str1);
// Search for the null character, but only so far.
const char *end = memchr(str2, '\0', len1);
size_t len2 = (end == NULL) ? len1 : end - str2;
// At this point len2 <= len1
memmove(str1 + len2, str1, len1 - len2); // Shift str1
memmove(str1, str2, len2); // Copy in str2
return str2[len2] == '\0'
}

Related

C: print the longest common prefix

Beginner programmer here, trying to figure out how to find and print the longest common prefix in C.
I have a base here for the program.
#include <stdio.h>
void findprefix(char *str1, char *str2, char *found);
int main(void) {
char str1[100];
char str2[100];
char found[10] = { '\0' };
printf("\nGive string 1: ");
scanf("%99s", str1);
printf("\nGive string 2: ");
scanf("%99s", str2);
//Print prefix
findprefix(str1, str2, found);
printf("%s", found);
return 0;
}
//Function to find the longest common prefix
void findprefix(char *str1, char *str2, char *found) {
int i, j;
for () {
if () {
}
}
}
The initial idea is to use a for loop and an if statement in the function but I'm not sure how.
This declaration
char found[10] = { '\0' };
is redundant and does not make a sense.
Also the function findprefix should return the length of the common prefix.
The function should be declared and defined the following way
size_t findprefix( const char *str1, const char *str2 )
{
size_t n = 0;
for ( ; *str1 && *str1 == *str2; ++str1, ++str2 )
{
++n;
}
return n;
}
And in main you can write
size_t n = findprefix( str1, str2 );
if ( n != 0 ) printf( "%.*s\n", ( int )n, str1 );
Here is a demonstration progarn.
#include <stdio.h>
size_t findprefix( const char *str1, const char *str2 )
{
size_t n = 0;
for ( ; *str1 && *str1 == *str2; ++str1, ++str2 )
{
++n;
}
return n;
}
int main( void )
{
const char *str1 = "Hello Word!";
const char *str2 = "Hello Kallum Smith";
size_t n = findprefix( str1, str2 );
if ( n != 0 ) printf( "\"%.*s\"\n", ( int )n, str1 );
return 0;
}
The program output is
"Hello "
Using the return value of the function you also can dynamically allocate an array or declare a variable length array where you can copy the prefix if it is required.
You have a good base, except you should define prefix with a length of 100 for pathological cases.
In the function, you should iterate with an index i starting at 0, comparing the characters from str1 and str2 at offset i and stop when they differ or when either one is a null byte (a char with the value 0), otherwise copying the byte to the found array at the same offset i.
After the loop. you would store a null byte in found at the offset where you stopped the iteration.
Finally, you would return to the caller.
Here is an example:
#include <stdio.h>
//Function to extract the longest common prefix
int findprefix(const char *str1, const char *str2, char *found) {
int i;
for (i = 0; str1[i] == str2[i] && str1[i] != '\0'; i++) {
found[i] = str1[i];
}
found[i] = '\0';
return i;
}
int main(void) {
char str1[100];
char str2[100];
char prefix[100];
printf("\nGive string 1: ");
if (scanf("%99s", str1) != 1)
return 1;
printf("\nGive string 2: ");
if (scanf("%99s", str2) != 1)
return 1;
//Print prefix
findprefix(str1, str2, prefix);
printf("%s\n", prefix);
return 0;
}

My own strcat function with pointers does not work right

I am new to pointers and want to learn them well. So this is my own attempt to write my strcat function. If I return just a it prints some binary things (I think it should print the solution), If I return *a it says seg fault core dumped I couldn't find the error. Any help is accepted thanks.
#include <stdio.h>
#include <string.h>
int main() {
char *strcaT();
char *a = "first";
char *b = "second";
printf("%s", strcaT(a, b));
return 0;
}
char *strcaT(char *t, char *s) {
char buffer[strlen(t) + strlen(s) - 1];
char *a = &buffer[0];
for (int i = 0; i < strlen(s) + strlen(t); i++, t++) {
if (*t == '\n') {
for (int i = 0; i < strlen(s);i++) {
buffer[strlen(t) + i] = *(s + i);
}
}
buffer[i] = *(t + i);
}
return a;
}
The code has multiple cases of undefined behavior:
you return the address of a local array in strcaT with automatic storage, which means this array can no longer be used once it goes out of scope, ie: when you return from the function.
the buffer size is too small, it should be the sum of the lengths plus 1 for the null terminator. You write beyond the end of this local array, potentially overwriting some important information such as the caller's framce pointer or the return address. This undefined behavior has a high chance of causing a segmentation fault.
you copy strlen(t)+strlen(s) bytes from the first string, accessing beyond the end of t.
It is unclear why you test for '\n' and copy the second string at the position of the newline in the first string. Strings do not end with a newline, they may contain a newline but and at a null terminator (byte value '\0' or simply 0). Strings read by fgets() may have a trailing newline just before the null terminator, but not all strings do. In your loop, the effect of copying the second string is immediately cancelled as you continue copying the bytes from the first string, even beyond its null terminator. You should perform these loops separately, first copying from t, then from s, regardless of whether either string contains newlines.
Also note that it is very bad style to declare strcaT() locally in main(), without even a proper prototype. Declare this function before the main function with its argument list.
Here is a modified version that allocates the concatenated string:
#include <stdio.h>
#include <stdlib.h>
char *strcaT(const char *s1, const char *s2);
int main() {
const char *a = "first";
const char *b = "second";
char *s = strcaT(a, b);
if (s) {
printf("%s\n", s);
free(s);
}
return 0;
}
char *strcaT(const char *t, const char *s) {
char *dest = malloc(strlen(t) + strlen(s) + 1);
if (dest) {
char *p = dest;
/* copy the first string */
while (*t) {
*p++ = *t++;
}
/* copy the second string at the end */
while (*s) {
*p++ = *s++;
}
*p = '\0'; /* set the null terminator */
}
return dest;
}
Note however that this is not what the strcat function does: it copies the second string at the end of the first string, so there must be enough space after the end of the first string in its array for the second string to fit including the null terminator. The definitions for a and b in main() would be inappropriate for these semantics, you must make a an array, large enough to accommodate both strings.
Here is a modified version with this approach:
#include <stdio.h>
char *strcaT(char *s1, const char *s2);
int main() {
char a[12] = "first";
const char *b = "second";
printf("%s\n", strcaT(a, b));
return 0;
}
char *strcaT(char *t, const char *s) {
char *p = t;
/* find the end of the first string */
while (*p) {
*p++;
}
/* copy the second string at the end */
while (*s) {
*p++ = *s++;
}
*p = '\0'; /* set the null terminator */
return t;
}
It is a very bad idea to return some local variable, it will be cleared after the function finishes its operation. The following function should work.
char* strcaT(char *t, char *s)
{
char *res = (char*) malloc(sizeof(char) * (strlen(t) + strlen(s) + 1));
int count = 0;
for (int i = 0; t[i] != '\0'; i++, count++)
res[count] = t[i];
for (int i = 0; s[i] != '\0'; i++, count++)
res[count] = s[i];
res[count] = '\0';
return res;
}
In the main function
char *strcaT();
It should be declared before main function:
char *strcaT(char *t, char *s);
int main() {...}
You returns the local array buffer[], it's is undefined behavior, because out of strcaT function, it maybe does not exist. You should use the pointer then allocate for it.
The size of your buffer should be +1 not -1 as you did in your code.
char *strcaT(char *t, char *s) {
char *a = malloc(strlen(t) + strlen(s) + 1);
if (!a) {
return NULL;
}
int i;
for(i = 0; t[i] != '\0'; i++) {
a[i] = t[i];
}
for(int j = 0; s[j] != '\0'; j++,i++) {
a[i] = s[j];
}
a[i] = '\0';
return a;
}
The complete code for test:
#include <stdio.h>
#include <stdlib.h>
char *strcaT(char *t, char *s);
int main() {
char *a = "first";
char *b = "second";
char *str = strcaT(a, b);
if (str != NULL) {
printf("%s\n", str);
free(str); // Never forget freeing the pointer to avoid the memory leak
}
return 0;
}
char *strcaT(char *t, char *s) {
char *a = malloc(strlen(t) + strlen(s) + 1);
if (!a) {
return NULL;
}
int i;
for(i = 0; t[i] != '\0'; i++) {
a[i] = t[i];
}
for(int j = 0; s[j] != '\0'; j++,i++) {
a[i] = s[j];
}
a[i] = '\0';
return a;
}
For starters the function strcaT should append the string specified by the second parameter to the end of the string specified by the first parameter. So the first parameter should point to a character array large enough to store the appended string.
Your function is incorrect because at least it returns a (invalid) pointer to a local variable length character array that will not be alive after exiting the function and moreover the array has a less size than it is required to store two strings that is instead of
char buffer[strlen(t) + strlen(s) - 1];
^^^
it should be declared at least like
char buffer[strlen(t) + strlen(s) + 1];
^^^
and could be declared as static
static char buffer[strlen(t) + strlen(s) + 1];
Also the nested loops do not make sense.
Pay attention that you should provide the function prototype before calling the function. In this case the compiler will be able to check passed arguments to the function. And the name of the function strcaT is confusing. At least the function can be named like strCat.
The function can be defined the following way
#include <stdio.h>
#include <string.h>
char * strCat( char *s1, const char *s2 )
{
char *p = s1 + strlen( s1 );
while ( ( *p++ = *s2++ ) );
return s1;
}
int main(void)
{
enum { N = 14 };
char s1[N] = "first";
char *s2 = "second";
puts( strCat( s1, s2 ) );
return 0;
}
The program output is
firstsecond
On the other hand if you are already using the standard C function strlen then why not to use another standard C function strcpy?
With this function your function could be defined more simpler like
char * strCat( char *s1, const char *s2 )
{
strcpy( s1 + strlen( s1 ), s2 );
return s1;
}
If you want to build a new character array that contains two strings one appended to another then the function can look for example the following way.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * strCat( const char *s1, const char *s2 )
{
size_t n1 = strlen( s1 );
char *result = malloc( n1 + strlen( s2 ) + 1 );
if ( result != NULL )
{
strcpy( result, s1 );
strcpy( result + n1, s2 );
}
return result;
}
int main(void)
{
char *s1 = "first";
char *s2 = "second";
char *result = strCat( s1, s2 );
if ( result ) puts( result );
free( result );
return 0;
}
Again the program output is
firstsecond
Of course calls of the standard C function strcpy you can substitute for your own loops but this does not make great sense.
If you are not allowed to use standard C string functions then the function above can be implemented the following way.
#include <stdio.h>
#include <stdlib.h>
char * strCat( const char *s1, const char *s2 )
{
size_t n = 0;
while ( s1[n] != '\0' ) ++n;
for ( size_t i = 0; s2[i] != '\0'; )
{
n += ++i;
}
char *result = malloc( n + 1 );
if ( result != NULL )
{
char *p = result;
while ( ( *p = *s1++ ) != '\0' ) ++p;
while ( ( *p = *s2++ ) != '\0' ) ++p;
}
return result;
}
int main(void)
{
char *s1 = "first";
char *s2 = "second";
char *result = strCat( s1, s2 );
if ( result ) puts( result );
free( result );
return 0;
}
I have changed your program to look like below:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char* strcaT();
char* a = "first";
char* b = "second";
printf("%s",strcaT(a,b));
return 0;
}
char* strcaT(char *t, char *s)
{
char* a = (char*)malloc(sizeof(char)*(strlen(t) + strlen(s) + 1));
for(int i=0; i<strlen(t); i++) {
a[i] = t[i];
}
for(int i=0; i<strlen(s); i++) {
a[strlen(t) + i] = s[i];
}
a[strlen(t)+strlen(s)] = '\0';
return a;
}
You are getting segfault because you are returning address of a local array which is on stack and will be inaccessible after you return. Second is that your logic is complicated to concatenate the strings.

Strings with malloc in C

I am writing a very simple program to copy a string using malloc.
#include <stdio.h>
#include <stdlib.h>
char * copyStr(char s[])
{
int len = strlen(s); //find length of s
char * copy;
copy = (char *)malloc(len); //dynamically allocate memory
int i;
for(i=0;i<len;i++)
{
copy[i]=s[i]; //copy characters
}
return copy; //return address
}
int main(int argc, char ** argv)
{
char * str;
str = "music is my aeroplane";
char * res;
res = copyStr(str);
printf("The copied string is : %s",res);
getch();
}
The desired output is:
The copied string is : music is my aeroplane
The current output is:
The copied string is : music is my aeroplaneOMEeJ8«≤╝
Any advice is appreciated.
A C string is null terminated. Add a null character (ie the char which ASCII code is 0) at end of the string :
char * copyStr(char s[])
{
size_t len = strlen(s); //find length of s
char * copy;
copy = (char *)malloc(len + 1); //dynamically allocate memory
/* One more char must be allocated for the null char */
size_t i;
for(i=0;i<len;i++)
{
copy[i]=s[i]; //copy characters
}
copy[i] = '\0'; // HERE
return copy; //return address
}
It is better to use size_t for the lengths because it is unsigned.
Strings in C are null-terminated.
The C programming language has a set of functions implementing
operations on strings (character strings and byte strings) in its
standard library. Various operations, such as copying, concatenation,
tokenization and searching are supported. For character strings, the
standard library uses the convention that strings are null-terminated:
a string of n characters is represented as an array of n + 1 elements,
the last of which is a "NUL" character.
In this case, you should have enough memory to store the original string contents and the "NUL" character (length+1). And don't forget to ensure the presence of the "NUL" character after the end of the string.
There are many possible ways to implement char * copyStr(char[]) function:
1) Your way (corrected):
char * copyStr(char s[])
{
int i;
size_t len = strlen( s );
char * p = (char*) malloc( len + 1 );
for( i = 0; i < len; i++ )
p[i] = s[i];
p[i] = '\0';
return p;
}
2) Using memcpy():
char * copyStr(char s[])
{
size_t len = strlen( s );
char * p = (char*) malloc( len + 1 );
memcpy( p, s, len );
p[ len ] = '\0';
return p;
}
3) Using strcpy():
char * copyStr(char s[])
{
size_t len = strlen( s );
char * p = (char*) malloc( len + 1 );
strcpy( p, s );
return p;
}
4) Using strdup():
char * copyStr(char s[])
{
return strdup(s);
}
Note: For every malloc() function call you need a free() function call, your main() needs a little modification for correctness:
int main( int argc, char ** argv )
{
char * str;
char * res;
str = "music is my aeroplane";
res = copyStr( str );
printf( "The copied string is : %s", res );
free(res); /* freedom */
getch();
return 0;
}
Hope it Helps!

Rotated strings

Write code to check if s2 is rotation of s1 using only one call to isSubString (ie. waterbottle is a rotation of erbottlewat).
I write program for this but i can't able to get the desired output. Please guide me where I am going wrong.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int isRotated(char *s1, char *s2);
int isSubstring(char *s1, char *s2);
int isRotated(char *s1, char *s2)
{
int r;
char s[100];
if(strlen(s1) == strlen(s2))
strcpy(s, s1);
r = isSubstring(s, s2);
strcat(s, s1);
return r;
}
int isSubstring(char *s1, char *s2){
if(strstr(s1, s2))
return 1;
else
return 0;
}
int main(void) {
char s1[100], s2[100];
printf("Enter the first String\n");
scanf("%s", s1);
printf("Enter the second String\n");
scanf("%s", s2);
if(isRotated(s1, s2)==1)
printf("%s and %s are rotated string\n", s1, s2);
else
printf("%s and %s are not rotated string\n", s1, s2);
return 0;
}
To check if s2 is rotation of s1, you may want to concentrate two s1s, and try finding s2 in the new string.
It is necessary to check the length of s1 and s2. For example, s1 is "ABCD", s2 is "CDA". Then s is "ABCDABCD". strstr(s, s2) == 1, but obviously, s2 isn't rotation of s1.
Also, I'd want to call strcmp() first, because I consider a "ABCD" as rotation of "ABCD" itself. However, this is only a matter of definition.
int isRotated(char *s1, char *s2)
{
char s[199];
if(strlen(s1) != strlen(s2))
return 0;
else if(strcmp(s1, s2) == 0)
return 1;
else
strcpy(s, s1);
strcat(s, s1);
return isSubString(s, s2);
}
BTW: "substring" is one word, so it might be better changing isSubString() to isSubstring()
If you do the comparison with strstr() you are searching a substring in the rotated string. So what you are doing is to find for example the string s1 ABCD in an other string s2 CDAB. So in fact s2 has no substring s1 in it and your function int isSubString(char *s1,char *s2) will always return false.
A simple solution for this would be not to compare s1 with s2 directly. You have to compare s2 to a doubled copy of s1: CDABCDAC, there you can see that this string contains a substring ABCD and your function will return true.
This would mean for your function:
int isRotated(char *s1,char *s2)
{
char s[200];
strcpy(s,s1); // Copy content of s1 to s
strcat(s,s1); // Append s again with the content of s1
if(strstr(s,s2))
return 1;
else
return 0;
}
How about this, using the concatenate-and-look-for-substring approach:
int isRotated(const char *s1, const char *s2)
{
const size_t l1 = strlen(s1);
const size_t l2 = strlen(s2);
if(l1 != l2)
return 0;
char joined[2 * l1 + 1];
memcpy(joined, s1, l1);
memcpy(joined + l1, s1, l1);
joined[2 * l1] = '\0';
return strstr(joined, s2) != NULL;
}
Basically uses more const, variable-length array to handle varying lengths, and memcpy() when we know the length we're copying.

What is wrong with my 'append' algorithm or code?

2 strings are given, second word will be append to first one and 3rd variable will store this. For example;
char *str1 = "abc";
char *str2 = "def";
char *str3 = "abcdef"; //should be
Here is my code, I get runtime error:
#include <stdio.h>
#include <malloc.h>
void append(char *str1, char *str2, char *str3, int size1, int size2)
{
int i=0;
str3 = (char*) malloc(size1+size2+1);
str3 = str1;
while (str2[i] != '\0') {
str3[i+size1] = str2[i];
i++;
}
str3[size1+size2] = '\0';
}
int main()
{
char *str1 = "abc";
char *str2 = "def";
char *str3;
append(str1, str2, str3, 3, 3);
return 0;
}
str3 = (char*) malloc(size1+size2+1);
str3 = str1;
Here's your problem. Doing this replaces the pointer to the correct amount of space from malloc to the pointer where str1 is contained. Keeping with your loop design, change this to:
str3 = malloc(size1+size2+1);
for (int j = 0; str1[j] != '\0'; j++)
str3[j] = str1[j];
Also, see this question/answer about casting the result of malloc in C:
Do I cast the result of malloc?
There is another issue with the code. You pass pointer by value. So any malloc inside a function will do only local changes. After function ends your pointer will still point to the old value. You should pass a pointer to pointer if you want to change it. See an example:
#include <stdio.h>
char *c = "Second";
void assign(char *s) { s = c; }
int main()
{
char *str = "First";
assign(str);
printf("String after assign: %s\n", str);
return 0;
}
After running the program you will see 'First' in you console. The correct code is:
#include <stdio.h>
char *c = "Second";
void assign(char **s) { *s = c; }
int main()
{
char *str = "First";
assign(&str);
printf("String after assign: %s\n", str);
return 0;
}
#include <stdio.h>
#include <stdlib.h> //to standard
#include <string.h>
char *append(const char *str1, const char *str2, int size1, int size2){
//parameter char *str3 is local variable.
//It is not possible to change the pointer of the original.
//str3 = str1;//<<-- memory leak
//str3[i+size1] = str2[i];//<<-- write to after str1(can't write!)
char *str3 = (char*) malloc(size1+size2+1);
memcpy(str3, str1, size1);//copy to alloc'd memory.
memcpy(str3 + size1, str2, size2);//copy to after str1
str3[size1+size2] = '\0';
return str3;
}
int main(){
char *str1 = "abc";
char *str2 = "def";
char *str3;
str3 = append(str1, str2, 3, 3);
printf("%s\n", str3);
return 0;
}

Resources