我的 main 函数中的 switch 案例 4 一直崩溃,无法修复。
我会稍微解释一下代码,希望你们能帮助我:
初始化函数
void function1(char[]);
声明字符串数组
const char *my_array[] = {
"Array of strings one",
"Array of strings two",
"Array of strings three"};
在主函数中循环遍历字符串数组(这工作正常,它打印字符串数组)
int i;
for (i=0; i < 3; i++) {
printf("%s\n", my_array[i]);
}
switch函数中的代码(还在main函数中)
case 4:
function1(my_array);
break;
我已经测试过,之前的所有代码都可以正常工作,问题出在这里(在 main 函数之外):
void function1(char my_array[]) {
for (i=0; i < 3; i++) {
printf("%s\n", my_array[i]);
}
printf("\n");}
当我执行 switch 的 case 4 时,它崩溃了。
日志给出的第 2 个警告:
warning: passing argument 1 of 'function1' from incompatible pointer type
warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat=]
抱歉,如果解释有点不清楚,我已尽我所能使其易于理解。
希望大家帮帮我,谢谢!!
最佳答案
第一次警告,即
warning: passing argument 1 of 'function1' from incompatible pointer type
讲故事:您正在传递一个字符指针数组,但函数声明说它需要一个简单的字符指针。
第二个警告从函数内部告诉你同样的事情:
warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat=]
格式需要 C 字符串,但您传递的是单个 char
*。
解决此问题所需要做的就是在 function1
的声明中添加一个缺少的星号:
void function1(const char *my_array[])
// ^^^^^ ^
同时,添加 const
以匹配 main
中 my_array
的声明。
*编译器说您传递的是 int
,而不是 char
,因为 printf
需要可变数量的参数,因此编译器将某些转换应用于函数的参数。其中一种转换是将所有 char
提升为 int
。
关于c - 在C中的函数中打印数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37224829/