字符串数组和 C 中的函数的问题

Problem with an array of strings and a function in C

我刚开始使用 C,我试图让一个包含 3 个字符串的数组通过一个函数。但是,在那个函数中,只剩下 1 个字符串,看起来甚至没有数组。我已经尝试了很多东西,但我似乎无法修复它。

#include <stdio.h>
#define NUM_WORDS 3
#define MAX_WORD_SIZE 64

void printStrings(char words[])
{
    //But now 'words' looks like this: "one"  
    for (int i = 0; i < NUM_WORDS; ++i)
        printf("%s", words[i]);
}

void main()
{
    char words[NUM_WORDS][MAX_WORD_SIZE] = { "one", "two", "three" };
    //At this point the array 'words' looks like this:  
    //{ "one", "two", "three" }
    printStrings(words);
}

您在 main 中对 words 的声明是正确的,但是要将二维数组传递给函数,您需要在函数中将其声明为二维数组。您当前的 printWords 声明仅将其参数声明为一维字符数组,这解释了为什么它不能正常工作。

正确声明的最低要求如下:

void printStrings(char words[][MAX_WORD_SIZE])

但是,在这种情况下,您可以选择这样做:

void printStrings(char words[NUM_WORDS][MAX_WORD_SIZE])

这有一个优点(和缺点),即对 can/should 传递给 printWords 的内容有更大的限制。这有点类似于以下两者之间的区别:

void function(char foo[])

接受任意大小的字符数组,

void function(char foo[FOO_SIZE])

表示它需要一个 FOO_SIZE 的数组,不大于也不小于。

请注意,您只能省略最外面(最左边)的维度,内部维度是必需的,以便编译器知道每个外部元素的最终大小。

你需要:

#include <stdio.h>
#define NUM_WORDS 3
#define MAX_WORD_SIZE 64

static void printStrings(char words[][MAX_WORD_SIZE])
{
    for (int i = 0; i < NUM_WORDS; ++i)
        printf("%s\n", words[i]);
}

int main(void)
{
    char words[NUM_WORDS][MAX_WORD_SIZE] = { "one", "two", "three" };
    printStrings(words);
    return 0;
}

你有一个完整的二维数组;您必须指定除第一个维度之外的所有维度的大小,如图所示。这与指针数组 (char *words[] = { "four", "five", "six", NULL };) 完全不同。然后参数类型将是 char **words,有点像 argvmain() 当它接受参数时。

请注意,标准 C 表示 main() returns an int。使用 void 仅在 Windows 上有效;其他地方都是错误的。

(我使用 static 是因为该函数不会在该源文件之外被引用。许多(大多数)人不会为此烦恼。我使用编译器选项使其成为必要。)

只需将函数参数更改为char char words[][MAX_WORD_SIZE]:

#include <stdio.h>
#define NUM_WORDS 3
#define MAX_WORD_SIZE 64

void printStrings(char words[][MAX_WORD_SIZE])
{
    //But now 'words' looks like this: "one"  
    for (int i = 0; i < NUM_WORDS; ++i)
        printf("%s", words[i]);
}

void main()
{
    char words[NUM_WORDS][MAX_WORD_SIZE] = { "one", "two", "three" };
    //At this point the array 'words' looks like this:  
    //{ "one", "two", "three" }
    printStrings(words);
}