繁体   English   中英

字符串数组和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])

这样做的优点(和缺点)意味着对可以/应该传递给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;
}

您拥有完整的2D阵列; 您必须指定除第一个尺寸外的所有尺寸的尺寸,如图所示。 这与指针数组完全不同( char *words[] = { "four", "five", "six", NULL }; )。 那么参数类型将是char **words ,当它接受参数时有点像argvmain()

请注意,标准C表示main()返回一个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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM