My task is to be able to concat two string and return a new string using pointers. It is supposed to return a new string but it returns a blank space currently. Here is my code:
char* concat(char* first, char* second){
int string1Len = strlen(first);
int string2Len = strlen(second);
int length = string1Len + string2Len;
char* string = malloc(sizeof(char)*length);
int i;
while(i < string1Len){
*(string + i) = *first;
first+= 1;
i+= 1;
}
while( i < length){
*(string + i) = *second;
second+= 1;
i+= 1;
}
return string;
}
iis not initialized to0.NULLto terminate the string?strlen()does not count the null byte that terminates a string, and that you must allocate space for the null byte, and set the last byte to zero before returning. Also,malloc()can fail — you should check the return value.strlen()is a part of the string library.