Error: function definition is not allowed here. How to correct this?

Error: function definition is not allowed here. How to correct this?

代码如下:

#include<stdio.h>

int main(){

// prints I stars

void printIStars(int i) {

  // Count (call it j) from 1 to i (inclusive)

  for (int j = 1; j <= i; j++) {

    // Print a star

    printf("*");

  }

}


// prints a triangle of n stars

void printStarTriangle(int n) {

  // Count (call it i) from 1 to n (inclusive)

  for (int i = 1; i <= n; i++) {

    // Print I stars

    printIStars (i);

    // Print a newline

    printf("\n");

  }

}

return 0;

}

对于这两个函数我都得到了错误

"function definition is not allowed here"

如何纠正?

您在 main 函数内部定义了两个函数,printIStarsprintStarTriangle,这是每个 C 实现都不允许的。 GCC 允许将其作为扩展,但 f.e。铛没有。当我使用 Clang 编译您的代码时,我对两个嵌套函数定义都收到了相同的警告。因此,您可能使用 Clang 或其他不支持嵌套函数定义的实现。

main 之外定义两个函数,它们在每个实现中都起作用。

除此之外,您从未调用过其中一个函数。

所以这是一个工作示例:

#include <stdio.h>

// function prototypes.
void printIStars(int i);              
void printStarTriangle(int n);

int main (void)
{
    printIStars(4);
    puts("");         // print a newline.
    printStarTriangle(7);
    return 0;
}

// function definitions

// prints I stars
void printIStars(int i) {

  // Count (call it j) from 1 to i (inclusive)
  for (int j = 1; j <= i; j++) {

    // Print a star
    printf("*");
  }
}


// prints a triangle of n stars
void printStarTriangle(int n) {

  // Count (call it i) from 1 to n (inclusive)

  for (int i = 1; i <= n; i++) {

    // Print I stars
    printIStars (i);

    // Print a newline
    printf("\n");
  }
}

输出:

****
*
**
***
****
*****
******
*******