그래서 두 개의 문자열을 C로 연결하는 함수를 만들어야합니다. 이 함수는 str1과 str2를 연결하여 새 문자열을 만듭니다. 함수는 malloc() 또는 calloc()을 호출하여 새 문자열에 메모리를 할당해야합니다. 함수는 새 문자열을 반환합니다.C에서 두 문자열 연결하기
주 테스트 함수에서 printf()를 호출하면 printf ("% s \ n", myStrcat ("Hello", "world!"))); 화면의 출력물은 Helloworld 여야합니다!
여기 내 코드가 있습니다. 왜 그것이 효과가 없는지 나는 이해할 수 없다. 그것은 아무것도하지 않습니다 ... 컴파일되고 실행되지만 아무것도 표시되지 않습니다.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *my_strcat(const char * const str1, const char * const str2);
int main()
{
printf("%s", my_strcat("Hello", "World")); // test function. Output of print statement is supposed to be HelloWorld
}
char *my_strcat(const char * const str1, const char * const str2)
{
char *temp1 = str1; // initializing a pointer to the first string
char *temp2 = str2; // initializing a pointer to the second string
// dynamically allocating memory for concatenated string = length of string 1 + length of string 2 + 1 for null indicator thing.
char *final_string = (char*)malloc (strlen(str1) + strlen(str2) + 1);
while (*temp1 != '\0') //while loop to loop through first string. goes as long as temp1 does not hit the end of the string
{
*final_string = *temp1; // sets each successive element of final string to equal each successive element of temp1
temp1++; // increments address of temp1 so it can feed a new element at a new address
final_string++; // increments address of final string so it can accept a new element at a new address
}
while (*temp2 != '\0') // same as above, except for string 2.
{
*final_string = *temp2;
temp2++;
final_string++;
}
*final_string = '\0'; // adds the null terminator thing to signify a string
return final_string; //returns the final string.
}
코드를 제대로 할 때 들여하십시오 C. – crashmstr
에'malloc'을 캐스팅하지 마십시오 여기에 게시. –
'* final_string = '\ 0'; return final_string;'--- 당신이 돌아 오는 것을보십시오, 여기. –