【发布时间】:2019-06-21 14:19:01
【问题描述】:
我正在尝试在 C 中实现某种“连接”以在一个字符串中使用几个值。
代码如下所示:
#include <stdio.h>
#define A "A"
int main() {
char *textArray[] = {"a", "b", "c"};
int intArray[] = {1, 2, 3};
int n;
// count intArray[] lengh
// example taken from the https://www.sanfoundry.com/c-program-number-elements-array/
n = sizeof(intArray)/sizeof(int);
int i;
char *concat;
for (i=0; i<n; i++) {
// check if values are accessible
printf("TEST: Macro: %s, textArray's value: %s, intArray's value: %d\n", A, textArray[i], intArray[i]);
// making concatenation here - this will work
concat = "Macro: " A " textArray's value: '' intArray's value: ''";
// this will NOT work
// expected result == 'Macro: A textArray's value: a intArray's value: 1' etc
// concat = "Macro: " A " textArray's value: " textArray[i] " intArray's value: " intArray[i];
printf("%s\n", concat);
}
return 0;
}
此代码仅在使用 A 宏的值时可以正常工作:
$ ./array_test TEST: Macro: A, textArray's value: a, intArray's value: 1 Macro: A textArray's value: '' intArray's value: '' TEST: Macro: A, textArray's value: b, intArray's value: 2 Macro: A textArray's value: '' intArray's value: '' TEST: Macro: A, textArray's value: c, intArray's value: 3 Macro: A textArray's value: '' intArray's value: ''
但如果我尝试使用textArray[i],即:
...
// making concatenation here - this will work
// concat = "Macro: " A " textArray's value: '' intArray's value: ''";
// this will NOT work
// expected result == 'Macro: A textArray's value: a intArray's value: 1' etc
concat = "Macro: " A " textArray's value: " textArray[i] " intArray's value: " intArray[i];
printf("%s\n", concat);
...
编译时出错:
$ gcc array_test.c -o array_test array_test.c: In function ‘main’: array_test.c:26:53: error: expected ‘;’ before ‘textArray’ concat = "Macro: " A " textArray's value: " textArray[i] " intArray's value: " intArray[i];
所以问题是:我在这里做错了什么以及实现目标的正确方法是什么?
UPD:最终目标是将一个字符串传递给像mysql_query() 这样的函数,例如mysql_query(conn, concat) 其中concat 将包含类似"INSERT INTO TableName VALUES('textValue', 'intValue')" 的值。
【问题讨论】:
-
为什么不
printf("Macro: %s %s: %d\n", A, textArray[i], intArray[i]);? -
@Someprogrammerdude 为我的目标添加了 UPD。
-
或者
sprintf,如果你想把它存储在一个变量中 -
如果你需要一个字符串,那么
snprintf代替? -
附带说明,如果您真的要将其传递给
mysql_query,通常不要。请改用参数绑定。串联可能导致 SQL 注入攻击。
标签: c arrays string concatenation