【发布时间】:2013-11-29 21:23:45
【问题描述】:
我正在尝试将单个数字连接到一个字符串:
include <stdio.h>
include <stdlib.h>
include <string.h>
int main() {
char *test="";
int i;
for (i = 0; i < 10; i++)
char *ic;
ic = malloc(2);
sprintf(ic, "%d", i);
// printf("%d\n", strlen(test));
if (strlen(test) == 0)
test = malloc(strlen(ic));
strcpy(test, ic);
} else {
realloc(test, strlen(test) + strlen(ic));
strcat(test, ic);
}
}
printf("%s\n", test);
// printf("%c\n", test);
free(test);
test = NULL;
return 0;
}
我的目标是让最终的结果printf ("%s", test) 成为0123456789。
【问题讨论】:
-
ic=malloc(2);- 为什么?为什么不char ic[2]?或者为什么不简单地使用'0' + <digit>来获取数字的字符表示? -
可能是因为这是一个学习练习。
-
没错,感谢您抽出宝贵时间
标签: c concatenation base