【问题标题】:How to add a string to a 2D array in C如何在C中将字符串添加到二维数组
【发布时间】:2015-06-11 07:50:08
【问题描述】:

我开始学习 C 并且遇到了将字符串输入添加到 2D 数组的问题,我能够正确获取字符串输入,但是当我尝试将字符串元素添加到数组时它不是按预期工作。打印数组时(这是我测试程序的方式),它将为数组中的每个索引分配一个字符而不是整个字符串。

这是我的查看代码,非常感谢您提前发布任何帮助。

#include <stdio.h>
main()
{
    char c_array[3][3];
    int x;
    int y;
    int z=10;
    int i_user_input;
    char c_name[256];


    for(x=0;x<=+2;x++)
    {
        for(y=0;y<=2;y++)
        {
            printf("\nPlease enter a name to the system:");
            scanf(" %s",&c_array[x][y]);
            printf("The string is %s\n",c_name);
            printf("Please press '1' if you would like to keep entering names\n");
            printf("Please press '2' if you would like to print the list of names:");
            scanf("%d",&i_user_input);
            if(i_user_input==1)
                continue;
            if(i_user_input==2)
                for(x=0;x<=2;x++)
                {
                    for(y=0;y<=2;y++)
                    {
                        printf("c_array[%d][%d]=%c\n",x,y,c_array[x][y]);
                    }
                }
        }

    }

}

示例输入“Penelope!”的输出如下所示

c_array[0][0]=P
c_array[0][1]=e
c_array[0][2]=n
c_array[1][0]=e
c_array[1][1]=l
c_array[1][2]=o
c_array[2][0]=p
c_array[2][1]=e
c_array[2][2]=!

【问题讨论】:

    标签: c arrays string 2d


    【解决方案1】:

    当您声明时: char c_array[3][3];

    这意味着您的二维数组的每个元素都是一个“char”(单个字符);不是“字符串”。

    要让每个元素都是字符串,您需要按以下方式声明您的数组: char 字符串数组[3][3][256];

    我不确定这是你想要做的。 Mw 感觉是你想要一个由 3 个元素组成的数组,其中每个元素都是一个字符串。在这种情况下,[3] 是不够的,你的字符串必须少于两个字符(第三个保留为终止零)。

    【讨论】:

      【解决方案2】:

      字符串不是一种类型。它们是一个值模式,就像你说 int 存储十的倍数,然后它以 0 结尾...如果你说 char 的数组存储一个字符串,那么它在第一个 @987654323 结束@, 看?我们可以将十的倍数存储在不同类型的整数变量中,字符串也是如此。

      字符串是值的模式,而不是类型。在选择我们想要使用的整数类型时,我们会考虑整数的范围。我们为小整数值(小于 32768)选择 int,为较大的值(小于 2147483648)选择 long,对于大于该值的值选择 long long。结果,我们根据我们期望的十的倍数选择正确的整数类型。同样对于字符串,我们需要确保字符串中的字符有足够的内存,最后是'\0'

      字符&amp;c_array[x][y] 的内存只够存储0 个字符,后面跟一个'\0';它仅对存储空字符串有用。也许您打算像这样声明c_array

      char c_array[3][3][256];
      

      在这种情况下,scanf 期望 %s 对应于 char * 类型的参数...但是您的编译器可能会警告您,&amp;c_array[x][y] 将具有 char (*)[256] 类型。如果要修复该警告,则需要从 scanf 代码中删除 &amp;

      if (scanf("%s", c_array[x][y]) != 1) {
          /* XXX: Handle an error here,                *
           * e.g. by exiting or returning or something */
      }
      

      当我们讨论该主题时,您会注意到我删除了多余的空间; %s 已经执行了 格式指令将执行的功能。我还写了代码来检查scanf的返回值,你应该...


      还记得我们如何选择用于存储数据的整数类型吗?另一个考虑因素是我们打算存储的数据是否可以否定。考虑一下:在您的代码中,xy 是否应该能够存储负值?负数组索引有什么意义?建议将所有数组索引声明为size_t。当您使用printf 打印size_t 值时,您需要使用%zu 格式说明符而不是%d


      char c_name[256];
      /* ... */
      printf("The string is %s\n",c_name);
      

      现在,如果字符串存储在c_array[x][y] 中,那么c_name 的意义何在?这是一个不必要的变量。请改用c_array[x][y]


      printf("\nPlease enter a name to the system:");
      

      在写入'\n' 之前,常见的实现通常会避免打印字符;该行是一次打印的,而不是一个字符一个字符的。结果,您可能会看到一些奇怪的行为,例如这条线没有在正确的时间出现。通过将'\n' 放在行的末尾而不是开头来解决此问题:

      printf("Please enter a name to the system:\n");
      

      ...或使用puts,它会自动为您添加一个'\n':

      puts("Please enter a name to the system:");
      

      ...或者使用fflush,即使没有'\n',它也会写入所有未写入的未写入数据:

      fflush(stdout);
      

      【讨论】:

        【解决方案3】:

        在您的代码中

        scanf(" %s",&c_array[x][y]);
        printf("The string is %s\n",c_name);
        

        这两种说法都是错误的。

        1. %s 需要一个指向数组的指针,而不是单个 char。要扫描单个char,您需要%c 格式说明符。
        2. printf() 中使用的c_name 未初始化。使用未初始化的值会调用 undefined behaviour

        解决方案:要逐个元素地输入,你可以这样做

        for(x=0; x<=2 ;x++)
            {
                printf("Start entering the name, one character at a time\n");
                for(y=0; y< 2; y++)                //note only '<' here
                {
                    scanf(" %c", &c_array[x][y]);  // note the leading space
                }
                c_array[x][y] = 0;                 //null termination of array to be used as string
            }
        

        【讨论】:

          【解决方案4】:

          如果要为数组中的每个索引分配一个字符串,则按如下方式创建数组:

          #include<stdio.h>
          int main(void) 
          {
              char a[2][10];
              int i=0;
              char temp[20];
              for(i=0;i<2;i++)
              {
                  scanf("%s",temp);
                  strcpy(a[i],temp);
              }
              printf("%s",a[0]);
              return 0;
          }
          

          您输入的每个字符串都将存储在数组的每个索引中。

          【讨论】:

          • 你确定scanf("%s",&amp;temp) 吗?
          • 是的。有用。你对此有什么困惑?
          • 应该不需要&amp;,对吧? temp 是一个数组(字符),即一个指针(指向一个字符)。
          • 是的。我检查一下。没有必要&即使它也没有问题。
          • 是的,它可以工作,因为 temp 是一个固定/声明的名称。如果它是动态分配的,您将丢失指针。我认为这相当令人困惑。人们已经很难理解指针了。
          【解决方案5】:
          #include <stdio.h>
          #include <string.h>
          
          int main(void){
              char c_array[3][3];
              int x;
              int y;
              //int z=10;//unused
              int i_user_input;
              char c_name[256];
          
              printf("\nPlease enter a name to the system:");
              scanf("%255s",c_name);
              printf("The string is %s\n",c_name);
              printf("Please press '1' if you would like to keep entering names\n");
              printf("Please press '2' if you would like to print the list of names:");
              scanf("%d", &i_user_input);
              if(i_user_input==1)
                  ;
              else if(i_user_input==2){
                  memcpy(c_array, c_name, sizeof(c_array));
                  for(x=0;x<3;x++){
                      for(y=0;y<3;y++){
                          printf("c_array[%d][%d]=%c\n", x, y, c_array[x][y]);
                      }
                  }
              }
          }
          

          #include <stdio.h>
          #include <stdlib.h>
          #include <string.h>
          
          #define SIZE 3
          
          int main(void){
              char *c_array[SIZE][SIZE] = { NULL };
              int x;
              int y;
              //int z=10;//unused
              int i_user_input;
              char c_name[256];
          
              for(x=0;x<SIZE;x++){
                  for(y=0;y<SIZE;y++){
                      printf("\nPlease enter a name to the system:");
                      scanf("%255s", c_name);
                      printf("The string is %s\n", c_name);
                      printf("Please press '1' if you would like to keep entering names\n");
                      printf("Please press '2' if you would like to print the list of names:");
                      scanf("%d", &i_user_input);
                      c_array[x][y] = strdup(c_name);
                      if(i_user_input==1){
                          continue;
                      }
                      if(i_user_input==2){
                          int x, y;//local variable
                          for(x=0;x<SIZE;x++){
                              for(y=0;y<SIZE;y++){
                                  if(c_array[x][y] != NULL)
                                      printf("c_array[%d][%d]=%s\n", x, y, c_array[x][y]);
                              }
                          }
                      }
                  }
              }
              for(x=0;x<SIZE;x++)
                  for(y=0;y<SIZE;y++)
                      free(c_array[x][y]);
          }
          

          【讨论】:

            【解决方案6】:

            为什么不在数组/矩阵中使用指针?

            #include <stdio.h>
            #include <string.h>
            
            main()
            {
            char *c_array[3][3];
            int x;
            int y;
            int z=10;
            int i_user_input;
            char c_name[256];
            
            for(x=0;x<=+2;x++)
            {
                for(y=0;y<=2;y++)
                {
                    printf("\nPlease enter a name to the system:");
                    scanf(" %s",c_name);
                    new_string = malloc(strlen(c_name)+1)
                    if (new_string == NULL) {
                     print("error allocating string\n")
                     exit(-1);
                    }
                    strcpy(new_string, c_name);
                    c_array[x][y] = new_string
            
                    printf("The string is %s\n",c_name);
                    printf("Please press '1' if you would like to keep entering names\n");
                    printf("Please press '2' if you would like to print the list of names:");
                    scanf("%d",&i_user_input);
                    if(i_user_input==1)
                        continue;
                    if(i_user_input==2)
                        for(x=0;x<=2;x++)
                        {
                            for(y=0;y<=2;y++)
                            {
                                printf("c_array[%d][%d]=%c\n",x,y,c_array[x][y]);
                            }
                        }
                }
            }
            for(x=0;x<=2;x++) {
             for(y=0;y<=2;y++) {
              free(c_array[x][y])
             }
            } 
            }
            

            上面的代码将输入字符串存储在数组的每个单元格中,如果这是您的目标的话。

            注意:我没有尝试过,所以可能会有细微的错误。我的意思是向您展示如何使用指针及其与数组的等价性。使用没有指针的 C 是没有意义的。 :)

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-06-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-07-02
              • 1970-01-01
              • 1970-01-01
              • 2011-06-22
              相关资源
              最近更新 更多