如何使用 for 循环在 C 中打印可变大小 "string"?

How can I print a variable size "string" in C using a for loop?

所以我上周开始学习 C,我正在尝试编写一个非常简单的程序,根据用户输入(金字塔高度)打印 # 个字符的金字塔。我能够编写一个工作代码来声明一个数组,其大小 = 用户允许的最大高度,但现在我想在不将 char 数组固定为指定大小的情况下执行此操作,也就是说,我想更新数组的大小金字塔的每一层(对于每个 for 循环传递)。程序输出如下所示:

上图的代码是:

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>

int main(void)

{
   int h;

   do
   {
       h = get_int("Height of Pyramid: ");
   }
   while (h < 1 || h > 8);

   char string[h*2+2];

   for (int i = 0; i < (h*2)+1; i++)
   {
       string[i] = ' ';
   }

   for (int i = 0; i < h; i++)
   {
       string[(h-1)-i] = '#';
       string[(h+2)+i] = '#';

       printf("%s\n",string);
   }
}

如您所见,金字塔的每一层都具有相同的大小。我想知道的是:如果用户输入的是 height = 4,则第一个打印数组(金字塔顶部)的大小应该为 6(2 个空格,1 #,两个空格,1 #),最后一个打印数组(金字塔的底部)的大小应为 8(3 #,两个空格,3 #)。到目前为止,我了解到我无法修改 C 中数组的大小,因此我需要分配内存并使用指针来实现这一点,但我无法理解如何做到这一点.下面是我到目前为止编写的代码,与前面的代码基本相同,但我知道我的数组定义是错误的。

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>

int main(void)

{
   int h;

   do
   {
       h = get_int("Height of Pyramid: ");
   }
   while (h < 1 || h > 8);

   char* string = malloc((h*2+2)*sizeof(char));

   for (int i = 0; i < h; i++)
   {
       int t = 0;
       do
       {
           string[(h+2)+t] = '#';
           string[(h-1)-t] = '#';
           t++;
       }
       while (t <= i);
    
       printf("%s\n",string);
   }
   free(string);
}

接下来是前面代码的输出,如您所见,它打印了一堆空的金字塔等级和金字塔底部的一些 # 字符。我将不胜感激有关如何解决此问题的任何指南。

您可以在循环中使用realloc()来增加数组的大小。

您还需要将 1 添加到字符串的空终止符的分配中,然后将其追加到数组中。

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <cs50.h>

int main(void)

{
   int h;

   do
   {
       h = get_int("Heigh of Pyramid: ");
   }
   while (h < 1 || h > 8);

   // Create initial string filled with spaces
   char* string = malloc(h + 2);
   memset(string, ' ', h+2);

   for (int i = 0; i < h; i++)
   {
       string = realloc(string, h + 2 + i + 1 + 1); // + 1 because i is zero-based, + 1 for null terminator
       string[h-1-i] = '#';
       string[h+2+i] = '#';
       string[h+2+i+1] = '[=10=]';
       printf("%s\n",string);
   }
   free(string);
}
#include <stdio.h>

int main(void) {
    int h = 7;
    char blocks[h];
    memset(blocks,'#',h);
    
    for(int i=0; i<h; ++i)
    {
        printf("%*.*s %.*s\n",h, i+1,blocks, i+1, blocks);
    }
    return 0;
}

输出

Success #stdin #stdout 0s 4268KB
      # #
     ## ##
    ### ###
   #### ####
  ##### #####
 ###### ######
####### #######