具有char数组参数的函数

Kam*_*mil 0 c arrays pointers parameter-passing

我正在尝试编写一个用于在C中为PIC微控制器打印文本的函数(我认为它基于gcc)。

void print(char[] text);

void print(char[] text)
{
    for(ch = 0; ch < sizeof(text); ch ++)
    {
        do_something_with_character(text[ch]);
    }
}
Run Code Online (Sandbox Code Playgroud)

并这样称呼它:

print("some text");
Run Code Online (Sandbox Code Playgroud)

我收到有关错误括号的编译器投诉。

  1. 这有什么问题?

  2. 在这种情况下,如何使用char数组指针?

Jon*_*art 5

如其他答案所述,您的语法不正确。方括号在之后 text

也显著重要性,sizeof不会做你希望在这里是什么:

void print(char[] text)
{
    for(ch = 0; ch < sizeof(text); ch ++)
                     ^^^^^^
Run Code Online (Sandbox Code Playgroud)

请记住,它sizeof是一个编译时运算符-编译代码时,编译器将其替换为大小。它可能无法在运行时知道大小。

在这种情况下,sizeof(text)总是返回return sizeof(void*),在大多数32位系统上为4。您的平台可能会有所不同。


您有两种选择:

  • 在另一个参数中传递长度以进行打印。
  • 将其char[]视为“ C字符串”,其中长度未知,但是字符串以NUL字符终止。

后者是您最好的选择,您应该替换char[]char*

在这里,我们使用以NUL结尾的字符串,并使用指针对其进行迭代:

void print(const char* text)
{
    const char* p;

    // Iterate over each character of `text`,
    // until we reach the NUL terminator
    for (p = text; *p != '\0'; p++) {

        // Pass each character to some function
        do_something_with_character(*p);
    }
}
Run Code Online (Sandbox Code Playgroud)


Lee*_*hem 5

正确的语法是

void print(char text[])
Run Code Online (Sandbox Code Playgroud)

要么

void print(char *text)
Run Code Online (Sandbox Code Playgroud)

在中print(),您不能使用sizeof运算符来找出字符串的长度text,您需要使用strlen()<string.h>首先包括)或测试是否text[ch]\0


Mah*_*mer 5

我会这样做:

void print(char *text);

void print(char *text)
   {
   while(*text)
      {
      do_something_with_character(*text);
      ++text;
      }
   }
Run Code Online (Sandbox Code Playgroud)