我正在尝试将有符号整数数组转换为字符指针。我编写了一个示例程序,如下所示。 预期输出为“10-26357-35” 请帮助我。
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int16_t frame_i[5] = {10, -26, 35, 7, -35};
size_t i;
char *s = malloc(5*2+1);
for(i = 0; i<5; i++) {
snprintf(s + i * 2, 3, "%hd", frame_i[i]);
}
return 0;
}
最佳答案
您必须考虑该标志。换句话说 - 你不能假设所有数字都是 2 个字符宽度。
尝试如下:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int16_t frame_i[5] = {10, -26, 35, 7, -35};
size_t i;
char *s = malloc(5*3+1); // Allocate memory to hold 3 chars for each number
char *tmp = s; // Add a tmp pointer to know how far you are
for(i = 0; i<5; i++) {
if (frame_i[i] >= 0) // Check the sign
{
snprintf(tmp, 3, "%02hd", frame_i[i]); // Requires 2 chars
tmp += 2;
}
else
{
snprintf(tmp, 4, "%03hd", frame_i[i]); // Requires 3 chars
tmp += 3;
}
}
// Print the result
printf("%s\n", s);
// Release memory
free(s);
return 0;
}
请注意,该解决方案仅适用于 -99 到 99 范围内的数字,并且它将在 -9 到 9 范围内的数字前面放置一个 0
。
利用 snprintf
返回字符数可以获得更通用(更简单)的解决方案,该解决方案可以处理更广泛的范围并且不在前面添加 0
打印。像这样的东西:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STRING_SIZE 1000
int main(void) {
int16_t frame_i[5] = {10, -26, 35, 7, -35};
size_t i;
int size_available = MAX_STRING_SIZE;
int cnt;
char *s = malloc(MAX_STRING_SIZE);
char *tmp = s;
for(i = 0; i<5; i++) {
cnt = snprintf(tmp, size_available, "%hd", frame_i[i]);
if (cnt <= 0 || cnt >= size_available)
{
printf("Error - snprintf failed or string too short\n");
free(s);
return(0);
}
size_available -= cnt;
tmp += cnt;
}
printf("%s\n", s);
free(s);
return 0;
}
关于将有符号整数数组转换为字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40639097/