如何将char *转换成char

2025-04-28 05:17:12
推荐回答(1个)
回答1:

字符数组不能直接赋值字符串。只能一个个赋值,或者用strcpy();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#include
#include
#include

int main()
{
char t[5] = {0};
char *s = (char *)malloc(strlen(t));

strcpy(t, "12345");
/*
或者 t[0] = '1'; t[1] = '2';...t[4] = '5';如果定义时没有初始化,做 ={0}操作,最好加上t[5] = '\0';
*/
s = t;

printf("%s\n", s);

return 0;
}

以上。linux头文件或许有些不同,编译不过的话请man strcpy 和 malloc查询正确的头文件