将int列表转换为字符串-C
我试图将整数列表转换为紧凑的字符串,但我会得到一个分段故障。 代码如下:
int *factors = job_factorization(number, size);
char buffer[250] = { 0 };
for (int i = 0; i < *size; i++) {
sprintf( &buffer[i], "%d ", *factors);
factors++;
}
job_factorization
函数返回列表的头部(它有效,我已经对其进行了测试),它将指向size size
指向的值设置为列表的实际大小(因此整数的数量)。 我不知道有什么问题,有人有任何想法吗?
I was trying to convert a list of integers into a compact string but I get a segmentation fault.
The code is the following:
int *factors = job_factorization(number, size);
char buffer[250] = { 0 };
for (int i = 0; i < *size; i++) {
sprintf( &buffer[i], "%d ", *factors);
factors++;
}
The job_factorization
function returns the head of the list (it works, I have already tested it), and it sets the value pointed to by size
to the actual size of the list (so the number of integers).
I cannot figure out what is wrong, does anyone have any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意以下备注:
sprintf(&amp; buffer [i],“%d”, *factor);
在上一个转换结束时不会转换数字。sprintf
不检查缓冲区溢出:如果size
足够大,它最终会在缓冲区的末端以外写入。修改
因素
可能不是一个好主意,因为使用后应释放此指针。这是一种替代方法:
您还可以使用2个循环来计算转换所需的尺寸并分配所需的空间。
Note these remarks:
sprintf( &buffer[i], "%d ", *factors);
does not convert the number at the end of the previous conversion.sprintf
does not check for buffer overflow: ifsize
is large enough, it will eventually write beyond the end of the buffer.modifying
factors
is probably not a good idea as this pointer should be freed after use.Here is an alternative:
You could also use 2 loops to compute the size needed for the conversion and allocate the space needed.