我使用C++长时间处理字符串操作但由于某种原因我必须在C中编写代码.我知道在C中,我必须先在字符串操作之前分配内存.我将整数数组转换为一个大字符串,例如
int data[]={1, 102, 3024, 2, 3, 50234, 23} => "1,102,3024,2,3,50234,23"
Run Code Online (Sandbox Code Playgroud)
我使用sprintf将数组中的每个数字转换为字符串,并使用strcat连接每个子字符串
char *s, *output_string;
int i, N;
// N is the size of the array and given as parameter of a function
for (i=0; i<N; i++)
{
sprintf(s, "%d", data[i]);
strcat(output_string, s);
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用.我想使用sprintf和strcat这些函数,我是否必须首先分配内存?但是数据[i]的位数是多少的,所以如何判断我应该提前分配多少内存?另外,我怎么知道我必须提前为output_string分配多少内存?谢谢
是的,您需要先为中间结果和最终结果分配空间.
让我们假设(为了参数)每个int可以产生最多10位数的输出:
char intermediate[11];
char *result = malloc(input_count * 11+1);
for (int i=0; i<input_count;i++) {
sprintf(intermediate, "%d", data[i]);
strcat(result, intermediate);
strcat(result, ",");
}
Run Code Online (Sandbox Code Playgroud)
如果你想要足够严重,你可以log10用来计算每个数字将产生的数字位数,然后只分配必要的空间,而不是像我在这里做的那样在最坏的情况下分配.
另请注意,在大多数情况下,如果可用,您可能会更好,snprintf而不是sprintf.这使您可以限制产生的输出量,确保不会溢出您提供的缓冲区.