我正在尝试将单个数字连接到一个字符串:
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) be 0123456789的结果。
发布于 2013-11-30 05:33:41
请记住,字符串以空字符结尾。为字符串分配内存时,必须为空值添加额外的字节。因此,您需要为每个malloc()和realloc()调用添加1。例如:
test = malloc(strlen(ic) + 1);还要记住,允许realloc()将变量“移动”到内存中的新位置。它可能需要这样做,以便找到足够的连续未分配空间。如果不能分配请求的内存,它也可以返回NULL,所以你应该这样调用它:
char *new_mem = realloc(test, strlen(test) + strlen(ic) + 1);
if (new_mem == NULL) {
// Not enough memory; exit with an error message.
} else {
test = new_mem;
}发布于 2013-11-30 05:37:00
以下是几个问题:
char *test=""; -将测试指向一个常量C字符串。您不需要对它进行编写,但是它很危险,而且可以用C++进行编译。""的类型是const char*.strlen,返回字符串的长度,而不是缓冲区的大小。您需要添加+1才能包含空字符。这是你最大的问题,ic这样的短的已知的固定大小的小缓冲区应该被分配到堆栈上。一个简单的char数组。你也忘了free()它。https://stackoverflow.com/questions/20293543
复制相似问题