So this is my code for appending string2 to string 1. Code works fine when I have added the line: s1[null_index]='\0';
but when i omit it adds the word 'road' one more time to the output...why is that? Why do I have to specify that the final value of null_index variabe is '\0'
....shouldnt the computer already know this since it does when I declare and assign in the beginning?
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
int main()
{
char s2[]="a lonely road";
char s1[]="Success is ";
int l=strlen(s1);
int null_index=l,i=0;
while(s2[i]!='\0')
{
s1[null_index]=s2[i];
i++;
null_index++;
}
s1[null_index]='\0';
printf("%s",s1);
}
The problem is that the arrays you have are of a fixed size. Once initialized, any indexing beyond the null-terminator will be out of bounds and lead to undefined behavior.
If you want to append to s1
then you need to explicitly set a size of the array, a size that fits both the strings (plus the terminator).
And when you append to s1
, the very first iteration of your loop you overwrite the terminator. Since you then don't copy the terminator from s2
you have to explicitly set the terminator of s1
at the appropriate place.