【问题标题】:How to use strset() in linux using c language如何使用c语言在linux中使用strset()
【发布时间】:2020-01-13 12:00:45
【问题描述】:

我不能在 C 中使用 strset 函数。我正在使用 Linux,并且我已经导入了 string.h,但它仍然不起作用。我认为Windows和Linux有不同的关键字,但我在网上找不到修复;他们都在使用 Windows。

这是我的代码:

   char hey[100];
   strset(hey,'\0');   

错误:: 警告:函数 strset; did you meanstrsep 的隐式声明? [-Wimplicit-function-declaration] strset(嘿, '\0');

^~~~~~strsep

【问题讨论】:

  • 这个函数应该做什么?

标签: c linux string string-function


【解决方案1】:

首先strset(或者更确切地说_strset)是一个Windows特有的功能,它不存在于任何其他系统中。通过阅读它的文档,它应该很容易实现。

但您还有一个次要问题,因为您将 未初始化 数组传递给函数,该函数需要一个指向以空字符结尾的字符串的第一个字符的指针。这可能会导致未定义的行为

解决这两个问题的方法是直接初始化数组:

char hey[100] = { 0 };  // Initialize all of the array to zero

如果您的目标是将现有的以 null 结尾的字符串“重置”为全零,请使用 memset 函数:

char hey[100];

// ...
// Code that initializes hey, so it becomes a null-terminated string
// ...

memset(hey, 0, sizeof hey);  // Set all of the array to zero

或者,如果您想具体模拟 _strset 的行为:

memset(hey, 0, strlen(hey));  // Set all of the string (but not including
                              // the null-terminator) to zero

【讨论】:

    【解决方案2】:

    strset 不是标准的 C 函数。您可以使用标准函数memset。它有以下声明

    void *memset(void *s, int c, size_t n);
    

    例如

    memset( hey, '\0', sizeof( hey ) );
    

    【讨论】:

      猜你喜欢
      • 2011-07-04
      • 2019-01-27
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 2016-03-23
      • 1970-01-01
      • 2011-09-28
      相关资源
      最近更新 更多