【问题标题】:storing standard inputs into dynamic memory in C将标准输入存储到 C 中的动态内存中
【发布时间】:2017-06-23 16:34:25
【问题描述】:

我目前正在使用 C 语言进行一些编码,只是为了提高我的 C 技能。我正在做的是将单词存储在分配的动态内存中,但在使用 **pointer 时遇到了一些困难......

例如,

while ((ch = getchar()) != EOF)

如果我输入abcd efgh,字符“abcd”应该存储在ptr[0][i]中,第二个字符“efgh”应该存储在ptr[1][i]中,这应该通过循环来完成。

我想通过初始化来实现,

char **ptr = (char**)malloc(sizeof(char*)*n);

这可能吗??

任何帮助将不胜感激!

【问题讨论】:

  • 不确定你的表达中的i 是什么意思。我假设你的意思是你想将字符串存储在ptr[0]ptr[1] 等位置。你的开始几乎是正确的。 You don't want to cast malloc return。此外,一旦分配了ptr,您将需要分配每个字符串指针,例如ptr[0] = malloc(sizeof(char) * string_buffer_length)
  • 是的,但这会分配 n 个 指针 指向任何内容。然后,您必须为每个指针分配一个字符缓冲区。

标签: c pointers computer-science


【解决方案1】:

这是一个将一些字符串存储在动态数组(char **)中的示例。

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

int main(void)
{
    char    **strings = NULL;
    size_t  nb_strings = 3;
    size_t  strings_length = 10;

    strings = malloc( sizeof(*strings) * nb_strings );
    // Now you can store 3 pointers to char

    for (size_t index = 0 ; index < nb_strings ; index++)
        strings[index] = malloc( sizeof(**strings) * strings_length );
        // Every pointer points now to a memory area of 10 bytes

    for (size_t index = 0 ; index < nb_strings ; index++)
    {
        strings[index][0] = '\0';
        strncat( strings[index], "string", strings_length - 1 );
        // You can store some strings now
    }

    for (size_t index = 0 ; index < nb_strings ; index++)
        printf("strings[%zu] = %s.\n", index, strings[index]);
    // You can check

    for (size_t index = 0 ; index < nb_strings ; index++)
        free(strings[index]);

    free(strings);
    // Do not forget to free

    return (0);
}

【讨论】:

    【解决方案2】:

    你需要了解 realloc()。你有两个级别的列表,你有一个单词列表,当输入新单词时必须扩展,每个单词都是一个字符列表。

    从一个空的单词列表开始

     char **words = 0;
     int Nwords = 0;
    

    还有一句空话

     char *word = 0;
     int wordlen = 0;
    

    正如你所做的那样,我们的主循环是按字符读取输入

     while( (ch = getchar()) != EOF)
     {
        /* logic here */
     } 
    

    那么逻辑是什么?

     while( (ch = getchar()) != EOF)
     {
        if(!isspace(ch))
        {
           /* add letter to word */
        }
        else
        {
           if(wordlen > 0)
           {
              /* add word to word list */
           }
        }
     }
    

    我可以填写 cmets,但那会为您完成。您使用 realloc() 为每个新条目增加缓冲区。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多