【问题标题】:How to create an array of strings in C? [duplicate]如何在 C 中创建一个字符串数组? [复制]
【发布时间】:2013-02-16 04:37:35
【问题描述】:

我正在从一本书中自学 C,并且我正在尝试创建一个填字游戏。我需要制作一个字符串数组,但不断遇到问题。还有,我对数组不太了解……

这是一段代码:

char word1 [6] ="fluffy", word2[5]="small",word3[5]="bunny";

char words_array[3]; /*This is my array*/

char *first_slot = &words_array[0]; /*I've made a pointer to the first slot of words*/

words_array[0]=word1; /*(line 20)Trying to put the word 'fluffy' into the fist slot of the array*/ 

但我不断收到消息:

crossword.c:20:16: warning: assignment makes integer from pointer without a cast [enabled by default]

不知道是什么问题...我试图查找如何制作字符串数组但没有运气

任何帮助将不胜感激,

山姆

【问题讨论】:

  • 尝试更多地研究数组pw1.netcom.com/~tjensen/ptr/pointers.htm
  • 顺便说一句 - char word1 [6] ="fluffy" - “蓬松”实际上是 7 个字符。在 C 中,字符串以 \0 结尾 - 它占用一个额外的字符。
  • const char* arr[] = { "literal", "string", "pointer", "array"};,并注意 const
  • &words[0] 呃...此时您似乎没有变量words。您是否在复制代码时出错或遗漏了什么?
  • @teahupoo 谢谢我去看看!

标签: c arrays string


【解决方案1】:
words_array[0]=word1;

word_array[0]char,而 word1char *。你的角色无法保存地址。

字符串数组可能看起来像这样:

char array[NUMBER_STRINGS][STRING_MAX_SIZE];

如果您想要一个指向字符串的指针数组:

char *array[NUMBER_STRINGS];

然后:

array[0] = word1;
array[1] = word2;
array[2] = word3;

也许你应该阅读this

【讨论】:

    【解决方案2】:

    声明

    char words_array[3];
    

    创建一个由三个字符组成的数组。您似乎想声明一个字符数组 pointers:

    char *words_array[3];
    

    你有一个更严重的问题。声明

    char word1 [6] ="fluffy";
    

    创建一个包含六个字符的数组,但您实际上告诉它有 七个 字符。所有字符串都有一个额外的字符'\0',用于表示字符串的结尾。

    要么声明数组大小为 7:

    char word1 [7] ="fluffy";
    

    或者忽略大小,编译器会自己算出来:

    char word1 [] ="fluffy";
    

    【讨论】:

      【解决方案3】:

      如果你需要一个字符串数组。有两种方式:

      1.二维字符数组

      在这种情况下,您必须事先知道字符串的大小。如下所示:

      // This is an array for storing 10 strings,
      // each of length up to 49 characters (excluding the null terminator).
      char arr[10][50]; 
      

      2。字符指针数组

      如下所示:

      // In this case you have an array of 10 character pointers 
      // and you will have to allocate memory dynamically for each string.
      char *arr[10];
      
      // This allocates a memory for 50 characters.
      // You'll need to allocate memory for each element of the array.
      arr[1] = malloc(50 *sizeof(char));
      

      【讨论】:

        【解决方案4】:

        也可以使用malloc()手动分配内存:

        int N = 3;
        char **array = (char**) malloc((N+1)*sizeof(char*));
        array[0] = "fluffy";
        array[1] = "small";
        array[2] = "bunny";
        array[3] = 0;
        

        如果您事先(在编码时)不知道数组中有多少个字符串以及它们的长度,那么这是一种方法。但是当它不再使用时,你必须释放它(调用free())。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-09-16
          • 2022-01-04
          • 2012-08-15
          • 1970-01-01
          • 1970-01-01
          • 2010-11-08
          • 2012-01-11
          相关资源
          最近更新 更多