代码之家  ›  专栏  ›  技术社区  ›  Anakin

为什么星号三角形不能大于23?

c
  •  1
  • Anakin  · 技术社区  · 7 年前

    我目前正在学习C编程,并完成了一个简单的练习。

    #include<stdio.h>
    #include<stdlib.h>
    
    char* nstars(int n);
    
    int main(void)
    {
        int sn;
        printf("Number of stars: ");
        scanf("%d", &sn);
        for(int i = 1; i <= sn; i++)
        {
            printf("\n%s", nstars(i));
        }
        return 0;
    }
    
    char* nstars(int n)
    {
        char* starstr = (char*) calloc(n, sizeof(char));
        for(int nt=0; nt < n; nt++)
        {
            starstr[nt] = '*';
        }
        return starstr;
    }
    

    上面的代码将打印如下内容

    sn=4
    *
    **
    ***
    ****
    

    sn

    为什么会这样?我该怎么修?

    2 回复  |  直到 7 年前
        1
  •  2
  •   John Bode    7 年前

    starstr 把绳子系起来,直到你穿到23号为止 只是碰巧 紧跟在

    至少 n+1个元素的宽度来解释终结符,所以你需要调整你的 calloc

    char *starstr = calloc( n + 1, sizeof *starstr );
    

    几个注意事项-首先,演员阵容 分配 从C89起不需要 2 . 第二,你可以使用 sizeof 在你的目标得到正确的类型大小-类型的 *starstr char ,所以 sizeof *starstr sizeof (char) . 1 ,但如果您决定使用“宽”字符类型(如 wchar_t ,您不必更改 分配 自称。

    nstars ,但你不会在完成后取消分配它。

    一旦

    int main( void )
    {
      ...
      char *starstr = calloc( n + 1, sizeof *starstr );
    
      /**
       * ALWAYS check the result of a malloc, calloc, or realloc call.
       */
      if ( !starstr )
      {
        fprintf( stderr, "Could not allocate memory for string - exiting\n" );
        exit( 0 );
      }
    
      for ( int i = 0; i < n; i++ )    // Each time through the loop, add an
      {                                // asterisk to the end of starstr,
        starstr[i] = '*';              // then print starstr.  
        printf( "%s\n", starstr );
      }
      free( starstr );
      ...
    }
    

    分配 如果将分配的内存归零,则不需要在添加新星号后显式编写字符串终止符。你用过吗 malloc 相反,你需要写作

    starstr[i] = '*';
    starstr[i+1] = 0;
    printf( "%s\n", starstr );
    


    1. 马洛克 , ,或 realloc 除非你
    2. C89允许隐式 int 声明,所以如果你忘了包括 stdlib.h 在作用域中,编译器将假定它返回 内景 如果您试图将结果分配给指针,则会发出诊断。但是,如果将结果强制转换为指针,则编译器 不会 内景 声明,所以这个特定的问题不再是一个问题了,但是最好还是离开这个问题。它使代码更易于阅读和维护。

        2
  •  2
  •   my_name    7 年前

    n + 1 对于 calloc

    还有:别忘了 free !

    char *

    #include<stdio.h>
    #include<stdlib.h>
    
    char* nstars(int n);
    
    int main(void)
    {
        int sn;
        printf("Number of stars: ");
        scanf("%d", &sn);
        for(int i = 1; i <= sn; i++)
        {
            char *str = nstars(i);
            printf("\n%s", str);
            free(str);
        }
        return 0;
    }
    
    char* nstars(int n)
    {
        char* starstr = (char*) calloc(n + 1, sizeof(char));
        for(int nt=0; nt < n; nt++)
        {
            starstr[nt] = '*';
        }
        return starstr;
    }