没有stdlib.h的动态结构和数据存储

时间:2019-03-11 22:50:59

标签: c data-structures

我曾经尝试过使用Google,但不确定如何用短语表达搜索结果。编程语言为C。给了我(作业)作业,该作业需要读取文本文件并在文本文件中输出唯一的单词。限制是唯一允许的导入为<stdio.h>。因此,有没有一种方法可以使用动态结构而不使用<stdlib.h>?是否有必要自行定义那些动态结构?如果已经在Stack Overflow上解决了此问题,请指出问题。

今天提供的说明是,现在允许的进口包括<stdlib.h>以及(虽然不是必需的或不希望的)使用<string.h>,这反过来又使这个问题更容易(我很想说些小事。

2 个答案:

答案 0 :(得分:2)

仅使用stdio.h不可能在c中编码动态数据结构。这可能是您的老师限制您仅使用stdio.h的原因之一-他们不希望您陷入尝试创建链接列表或存储唯一单词的麻烦。

但是,如果考虑一下,就不需要动态数据结构。这里有一些尝试:(1)复制源文件。 (2)声明结果文本文件以存储您的结果。 (3)将源文件中的第一个单词复制到结果文件中。然后遍历您的源文件并删除该单词的每个副本。现在该词不可能有任何重复。然后移至下一个单词,然后复制并删除。

完成后,您的源文件应该为空(因此需要备份),结果文件中应具有原始源文件中每个唯一单词的副本。

这种方法的好处是它不需要您知道(或猜测)初始源文件的大小。

答案 1 :(得分:1)

同意以上关于“带有任意约束的练习”的观点,主要用于说明讲师最喜欢的宠物。

但是,如果您被允许天真的话,您可以按照别人所说的做,并假设唯一字符串数组的最大大小并使用一个简单的缓冲区。我写了一些存根,说明了我的想法。但是,免责声明是我不是一个“真正的程序员”,但随之而来的是所有不良习惯和知识空白。 我显然也忽略了读取文件和过滤唯一单词的主题。

#include <stdio.h>                                       // scanf, printf, etc.
#include <string.h>               // strcpy, strlen (only for convenience here)

#define NUM_STRINGS 1024                           // maximum number of strings
#define MAX_STRING_SIZE 32      // maximum length of a string (in fixed buffer)


char fixed_buff[NUM_STRINGS][MAX_STRING_SIZE];
char * buff[NUM_STRINGS]; // <-- Will only work for string literals OR
                          // if the strings that populates the buffer
                          // are stored in a separate location and the
                          // buffer refers to the permanent location.

/**
 * Fixed length of buffer (NUM_STRINGS) and max item length (MAX_STRING_SIZE)
 */
void example_1(char strings[][MAX_STRING_SIZE] )
{
  // Note: terminates when first item in the current string is '\0'
  //       this may be a bad idea(?)
  for(size_t i = 0; *strings[i] != '\0'; i++)
    printf("strings[%ld] : %s (length %ld)\n", i, strings[i], strlen(strings[i]));
}


/**
 * Fixed length of buffer (NUM_STRINGS), but arbitrary item length
 */
void example_2(char * strings[])
{
  // Note: Terminating on reaching a NULL pointer as the number of strings is
  //       "unknown".
  for(size_t i = 0; strings[i] != NULL; i++)
    printf("strings[%ld] : %s (length %ld)\n", i, strings[i], strlen(strings[i]));
}

int main(int argc, char* argv[])
{

  // Populate buffers
  strncpy(fixed_buff[0], "foo", MAX_STRING_SIZE - 1);
  strncpy(fixed_buff[1], "bar", MAX_STRING_SIZE - 1);

  buff[0] = "mon";
  buff[1] = "ami";

  // Run examples
  example_1(fixed_buff);
  example_2(buff);

  return 0;
}
相关问题