c - 在C中的函数中打印数组中的字符串

标签 c arrays string

我的 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 以匹配 mainmy_array 的声明。

*编译器说您传递的是 int,而不是 char,因为 printf 需要可变数量的参数,因此编译器将某些转换应用于函数的参数。其中一种转换是将所有 char 提升为 int

关于c - 在C中的函数中打印数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37224829/

相关文章:

c - 用 c 编写我自己的 shell - free() 导致问题

c - GTK+ 将笔记本标签放在工具栏/其他小部件的顶部

c - SO_SNDBUF 小时阻塞 0.04 秒

c - 在 c 中跳过空格但不换行而不中断并继续

java - 如何根据用户输入实例化数组

java - 如何将图像添加到图像数组?

c# - 使用 '+' 运算符的字符串连接

没有 C 标准库的 C 程序。如何?

javascript - 为什么我的字符串返回 "&#39;"

java - 从字符串中命名一个对象