使用变量将元素输入到char数组中

时间:2016-04-05 13:00:22

标签: c arrays char

我需要输入一个元素static const char [].我已尝试使用snprintfstrcat,但它不适用于我的情况因为char数组包含一些NULL }字符。

    char SBP_BASE_LAT[] = "surveyed_position""\x00""surveyed_lat""\x00";

我有类型为float的变量 position_lati ,我想将其输入 SBP_BASE_LAT ,如

    float position_lati = 43.456745;
    char SBP_BASE_LAT[] = "surveyed_position""\x00""surveyed_lat""\x00"["%f",position_lati];

解决方案是什么? 感谢;

1 个答案:

答案 0 :(得分:0)

您提交的此声明......

char SBP_BASE_LAT[] = "surveyed_position""\x00""surveyed_lat""\x00";

...将SBP_BASE_LAT声明为char的数组,其大小派生自其初始化程序 - 32,包括额外的终止符,如果我已正确计数的话。数组元素不是const

在数组的初始值设定项中包含空字节是合法的,但这样做的有用性似乎值得怀疑。处理字符串的所有标准函数都会将第一个嵌入的空字节解释为字符串终止符,如果这是你想要的,那么它就不清楚为什么你提供一个更长的初始化器。

  

我有float类型的变量position_lati,我想将它输入到SBP_BASE_LAT [...]

您不能通过初始化程序执行此操作,因为初始化程序必须是编译时常量。你可以在运行时这样做:

float position_lati = 43.456745;
/* plenty of extra space to append the formatted value: */
char SBP_BASE_LAT[50] = "surveyed_position""\x00""surveyed_lat""\x00";
int base_lat_end;

/* 
 * compute the combined length of the first two zero-terminated
 * segments of SBP_BASE_LAT
 */
base_lat_len = strlen(SBP_BASE_LAT) + 1;
base_lat_len += strlen(SBP_BASE_LAT + base_lat_len) + 1;

/*
 * Format the value of position_lati into the tail of
 * SBP_BASE_LAT, following the second embedded zero byte.
 */
sprintf(SBP_BASE_LAT + base_lat_len, "%9.6f", position_lati);

当然,所有人都认为position_lati的值直到运行时才知道。如果在编译时已知,那么您可以将该值直接放入数组初始值设定项中。

另外,如果您的数组实际上是const,那么在初始化之后就无法修改其内容,因此基于sprintf()的方法(如我描述的方法)将无效。

相关问题