C语言 复制字符串 malloc
#include <stdio.h>
#include <string.h>
typedef void(*str_cpy_slk)(char *name);
void test(str_cpy_slk cb);
void call_back(char *name);
char *test_name = NULL;
int main(void)
{
test(call_back);
printf("name:%s\n", test_name);
return 0;
}
void test(str_cpy_slk cb)
{
char myname[8] = {0};
snprintf(myname, sizeof(myname), "%s", "slk");
printf("myname:%s\n", myname);
cb(myname);
}
void call_back(char *name)
{
test_name = name;
printf("test_name:%s\n", test_name);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef void(*str_cpy_slk)(char *name);
void test(str_cpy_slk cb);
void call_back(char *name);
char *test_name = NULL;
int main(void)
{
test(call_back);
printf("name:%s\n", test_name);
free(test_name);
return 0;
}
void test(str_cpy_slk cb)
{
char myname[8] = {0};
snprintf(myname, sizeof(myname), "%s", "slk");
printf("myname:%s\n", myname);
cb(myname);
}
void call_back(char *name)
{
test_name = (char *)malloc(strlen(name) + 1);
snprintf(test_name, strlen(name) + 1, "%s", name);
printf("test_name:%s\n", test_name);
}