0
我分配了足夠的內存父字符串,檢查所有的空值,並在年底通過「\ 0」終止父字符串。分段故障而連接兩個字符串
有在這條線分割故障:
*arg_parent = *arg_child;
我要去哪裏錯了?
#include <stdio.h>
#include <stdlib.h> // malloc
int my_strcat (char* arg_parent, char* arg_child)
{
if (arg_parent != NULL)
{
// Get to the end of the parent string.
while (*arg_parent != '\0')
arg_parent++;
// Concatinate child string to the end of the parent string, byte by byte
// till the child string ends.
while (*arg_child != '\0')
{
*arg_parent = *arg_child;
arg_parent++;
arg_child++;
}
// Append '\0' at the end of the parent string which now has the child string
// joined to it.
*arg_parent = '\0';
return 0;
}
else
return -1;
}
int main()
{
printf ("\nsdfsdf\n");
char* first_name = malloc (sizeof (char*) * 20);
first_name = "ani\0";
char last_name[4] = {'s', 'h', 'a', '\0'};
int return_value = my_strcat (first_name, last_name);
if (return_value == 0)
printf ("\nfirst_name: %s\n", first_name);
else
printf ("\nmmmmmmmmmmmm\n");
return 0;
}
要使用開始,替換'字符*如first_name = malloc的(的sizeof(字符*)* 20);'與'字符* first_name的= malloc(sizeof(char)* 20);'或'char * first_name = malloc(20);' –