Old answer below
You can initialize a string with strcpy, like in your code, or directly when declaring the char array.
char a1[100] = "Vivek";
Other than that, you can do it char-by-char
a1[0] = 'V';
a1[1] = 'i';
// ...
a1[4] = 'k';
a1[5] = '\0';
Or you can write a few lines of code that replace strcpy and make them a function or use directly in your main function.
Old answer
You have
0 1 2 3 4 5 6 7 8 9 ...
a1 [V|i|v|e|k|0|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_]
b1 [R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_|_|_|_|_|_]
and you want
0 1 2 3 4 5 6 7 8 9 ...
a1 [V|i|v|e|k|R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_]
so ...
a1[5] = 'R';
a1[6] = 'a';
// ...
a1[12] = 'l';
a1[13] = '\0';
but with loops and stuff, right? :D
Try this (remember to add missing bits)
for (aindex = 5; aindex < 14; aindex++) {
a1[aindex] = b1[aindex - 5];
}
Now think about the 5 and 14 in the loop above.
What can you replace them with? When you answer this, you have solved the programming problem you have :)
Answer from pmg on Stack OverflowHow can I concatenate two strings in C?
What is the difference between strcat() and strncat() for concatenating two strings?
What is string concatenation in C programming?
Old answer below
You can initialize a string with strcpy, like in your code, or directly when declaring the char array.
char a1[100] = "Vivek";
Other than that, you can do it char-by-char
a1[0] = 'V';
a1[1] = 'i';
// ...
a1[4] = 'k';
a1[5] = '\0';
Or you can write a few lines of code that replace strcpy and make them a function or use directly in your main function.
Old answer
You have
0 1 2 3 4 5 6 7 8 9 ...
a1 [V|i|v|e|k|0|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_]
b1 [R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_|_|_|_|_|_]
and you want
0 1 2 3 4 5 6 7 8 9 ...
a1 [V|i|v|e|k|R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_]
so ...
a1[5] = 'R';
a1[6] = 'a';
// ...
a1[12] = 'l';
a1[13] = '\0';
but with loops and stuff, right? :D
Try this (remember to add missing bits)
for (aindex = 5; aindex < 14; aindex++) {
a1[aindex] = b1[aindex - 5];
}
Now think about the 5 and 14 in the loop above.
What can you replace them with? When you answer this, you have solved the programming problem you have :)
char a1[] = "Vivek";
Will create a char array a1 of size 6. You are trying to stuff it with more characters than it can hold.
If you want to be able to accommodate concatenation "Vivek" and "Ratnavel" you need to have a char array of size atleast 14 (5 + 8 + 1).
In your modified program you are doing:
char *a1=(char*)malloc(100); // 1
a1 = "Vivek"; // 2
1: Will allocate a memory chunk of size 100 bytes, makes a1 point to it.
2: Will make a1 point to the string literal "Vivek". This string literal cannot be modified.
To fix this use strcpy to copy the string into the allocated memory:
char *a1=(char*)malloc(100);
strcpy(a1,"Vivek");
Also the for loop condition i<strlen(b1)-1 will not copy last character from the string, change it to i<strlen(b1)
And
a1[i]='\0';
should be
a1[i + len]='\0';
as the new length of a1 is i+len and you need to have the NUL character at that index.
And don't forget to free your dynamically allocated memory once you are done using it.
I didn't really change much in your program, but here's what I have (modified from yours) and it works.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char s1[100], s2[100];
size_t i, s1l, s2l, total;
puts("First string?");
fgets(s1, sizeof(s1), stdin);
s1[strlen(s1) - 1] = 0x00;
puts("Second string?");
fgets(s2, sizeof(s2), stdin);
s2[strlen(s2) - 1] = 0x00;
s1l = strlen(s1);
s2l = strlen(s2);
total = s1l + s2l;
for(i = s1l; i <= total; i++)
{
s1[i] = s2[i - s1l];
}
puts(s1);
return(0);
}
Using your program verbatim, the problem was that since the length of s1 was changing at each iteration of the loop, the strlen(s1) in the check kept increasing in value so you would basically end up with a mostly infinite loop...at least until it encountered some random null byte. However, when taking the length of the strings before hand, the loop terminus count does not change which results in the proper output. My code will compile and run correctly on a FreeBSD 10.2 system using the clang compiler.
As a side note, DO NOT return void on main. ALWAYS return int. Also specify the library headers that you plan to use.
EDIT: I modified the code to use fgets instead of gets since gets is completely unsafe. It does not check buffer sizes so you can easily have a buffer overflow.
The length of s1 is getting changed at runtime, making your index i incorrect. Try something like below:-
l = strlen(s1);
for(i = 0; i < strlen(s2); i++)
{
s1[l++] = s2[i];
}
s1[l] = '\0';
Suppose s1 = "hello" and s2 = "world", then in the first iteration length of s1 = 5 and index for s2 = 0(i- length(s1)); works well. But in the second iteration length(s1) = 6 and index for s2 = 0(i-length(s1)). so index for taking the character from s2 is not changing. This was about the problem in your implementation, though you should an efficient way by using sprintf.
sprintf(s1, "%s%s", s1, s2);
char *myconcat(const char *s1, const char *s2)
{
size_t len1,len2;
char *result = malloc((len1 = strlen(s1)) + (len2 = strlen(s2)) + 1);
if(result)
{
memcpy(result, s1, len1);
memcpy(result + len1, s2, len2 + 1);
}
return result;
}
You have s="computer" when passed into a function, and then on the very first line you reassign it with malloc, so "computer" is gone. You can debug your program step by step, or just print the values to the console. This will help you to find the error.
I expect they wanted something like this:
void mystrcat(char * dest, const char * src)
{
//advance dest until we find the terminating null
while (*dest) ++dest;
//copy src to dest including terminating null, until we hit the end of src
//Edit: originally this:
//for (; *dest = *src, *src; ++dest, ++src);
//...which is the same as this
for (; *dest = *src; ++dest, ++src);
}
It doesn't return the end of the concatenated string like the real strcat, but that doesn't seem to be required.
I don't necessarily know if this sort of thing is a good interview question - it shows that you can code tersely, and that you know what strcat does, but that's about it.
Edit: as aib writes, the statement
while (*dest++ = *src++);
...is perhaps a more conventional way of writing the second loop (instead of using for).
Given that the task was to concatenate two strings, not to create a duplicate of strcat, I'd go with the simple option of creating a completely new string that is a combination of the two.
char buffer[REASONABLE_MAX] = {0};
snprintf(buffer, REASONABLE_MAX - 1, "%s%s", string1, string2);
In main you declared character arrays with three elements
char string1[3] = "abc";
//...
char string2[3] = "def";
These arrays do not contain strings because they do not store the terminating zero character '\0' of the string literals used as initializers. The first array contains three characters { 'a', 'b', 'c' } and the second array contains these three characters { 'd', 'e', 'f' }.
Then you applied the standard string function strlen to these arrays which expects that passed to it arrays contains strings. That is the function calculates the number of characters in a string by counting characters until the terminating zero character is encountered. As the arrays do not contain the terminating zero character '\0' that is as the arrays do not contain strings the calls of strlen invoke undefined behavior.
If you want to append one string to another string then the destination character array shall have enough size to be able to accommodate the second string.
Thus the function main can look the following way
int main( void ) {
char string1[7] = "abc";
char string2[] = "def";
printf( "Resultant string = %s\n", strconcatenate( string1, string2 ) );
return 0;
}
Now the both arrays string1 and string2 contain strings. Moreover the array string1 reserved enough space to accommodate the string stored in the array string2.
The declaration of the function strconcatenate should be similar to the declaration of the standard C function strcat.
char * strconcatenate( char *string1, const char *string2 );
That is the second parameter should have the qualifier const because the passed array is not changed within the function and the function should return the destination array that will contain the concatenated strings.
The function definition will look the following way
char * strconcatenate( char *string1, const char *string2 )
{
for ( char *p = string1 + strlen( string1 ); *p++ = *string2++; );
return string1;
}
There are multiple problems in your code:
- [major]
char string1[3] = "abc";defines the destination array with a size of 3 bytes which does not have a enough space for the string"abc"including its null terminator and definitely not long enough to receive the extra characters fromstring2at the end. Change this tochar string1[7] = "abc"; - [major]
char string2[3] = "def";defines the source array with a size of 3 bytes which does not have a enough space for the string"def"including its null terminator, hence will not be null terminated. - [major]
string1[strlen(string1) - 1] = '\0';overwrites the last character ofabc, this not necessary. - [major] same remark for
string2[strlen(string2) - 1] = '\0'; - [minor]
string2should be defined asconst char *invoid strconcatenate(char *string1, char *string2) - [minor]
iandjshould be defined with typesize_t - [minor] for compatibility with the standard function
strcat,strconcatenateshould have a return type ofchar *and return the pointer to the destination array. Yet, As commented by Jonathan Leffler, a more useful design for the return value is to return a pointer to the null at the end of the concatenated string. You already know where the start of the string is; that isn't very interesting information. But knowing where the end of the string is after concatenation โ that is useful information which only the concatenate function is privy to. โ
Here is a modified version:
#include <stdio.h>
#include <string.h>
char *strconcatenate(char *string1, const char *string2) {
char *p = string1 + strlen(string1);
while ((*p = *string1) != '\0') {
string1++;
p++;
}
return string1; /* strcat semantics */
//return p; /* alternative semantics */
}
int main() {
char string1[7] = "abc";
char string2[] = "def";
strconcatenate(string1, string2);
printf("Resultant string = %s\n", string1);
return 0;
}