菜鸟,正在研究一个加密问题,我想遍历 C 数组中的组合,即 aaa、aab、aac、aba 等,然后将每个组合传递给一个函数(以检查该组合是否是正确的代码)。
我可以毫无问题地打印我想要的内容,即 aa、ab、ba、bb,但无法将这些值放入我的临时变量中。
#include <stdio.h>
int main(void) {
char *word = "ab";
char * temp[3];
//temp[2] = '\0';
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
temp[0] = &word[i];
temp[1] = &word[j];
printf("%s\n", *temp);
// printf("%c", word[i]);
// printf("%c\n", word[j]);
// pass_temp_to_function(temp);
}
}
return 0;
}
我得到了 ab、ab、b、b,而我应该得到 aa、ab、ba、bb(使用我上面的代码),但不知道为什么或如何更正它或以其他方式找到答案,因此我的菜鸟问题。
最佳答案
看起来你已经仔细地编写了它以创建零警告,即使它是非常错误的,具有各种字符串数组和指向字符的指针。
你想要一个包含 2 个字符的单个字符串,因为一个包含 3 个字符的数组就足够了:
char temp[3];
temp[2] = '\0';
...
temp[0] = word[i];
temp[1] = word[j];
puts(temp); // less typing but essentially the same as printf("%s\n", temp);
关于c - 如何在 C 中的 for 循环中分配给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55315764/