I read a article from https://blog.holbertonschool.com/code-review-string-concatenation-in-c/ which show the concatenation of two char arrays in c (64-bit,linux),then I got the problems:
Here is the code :
#include <stdio.h>
int main(void)
{
char aa[] = "Studytonight ";
char bb[] = "- Bestplace to learn";
char *a;
char *b;
printf("aa [%s]\n", aa);
printf("bb [%s]\n", bb);
a = aa;
b = bb;
while (*a)
{
a++;
}
while (*b)
{
*a = *b;
b++;
a++;
}
*a = '\0';
printf("The string after concatenation is: %s\n", aa);
printf("bb is now [%s]\n", bb);
system("pause");
return (0);
}
Here is the result in article https://blog.holbertonschool.com/code-review-string-concatenation-in-c/,what I want to know is the second and third problem,I do not need a function already exist to concatenate two char arrays. enter image description here
You are trying to append bytes to string aa, but there is only enough bytes to hold its own contents. If you want to actually add more bytes to it you should initially allocate larger array. Like this:
char aa[80] = "Studytonight ";
Here 80 is an arbitrary "large enough" number -- your array will have some extra space in the end where you can add bytes from string bb.
when concatenating two strings,
the resultant buffer must be long enough to hold both strings + 1. The +1 is for the NUL termination character.
the function: strcat()
(prototyped in string.h
) performs the concatenation for you.
Suggest:
#include <stdio.h> // puts()
#include <string.h> // strlen(), strcat()
int main( void )
{
char aa[] = "Studytonight ";
char bb[] = "- Bestplace to learn";
char cc[ strlen( aa ) + strlen( bb ) + 1 ];
strcpy( cc, aa );
strcat( cc, bb );
puts( cc );
}
Note: not every OS 'shell' has a 'pause' command, so suggest using (for portability):
int ch;
while( (ch = getchar()) != '\n' && ch != EOF ){;}
getchar();
Note: the linked code contains undefined behavior. This is because it writes beyond the end of the buffer aa[]
. This can result in 'stack smashing' or even a seg fault event.
main
char *mystrcat(char *dest, const char *src)
{
char *ret = dest;
while(*dest) dest++;
while((*dest++ = *src++));
return ret;
}
char aa[] = "Studytonight ";
char bb[] = "- Bestplace to learn";
char cc[sizeof(aa) + sizeof(bb) - 1] = {0};
or
#define STUDY "Studytonight "
#define BEST "- Bestplace to learn"
char aa[sizeof(BEST) + sizeof(STUDY) - 1] = STUSY; //aa has enough space to accommodate both strings
char bb[] = BEST;
and the bath examples:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.