【问题标题】:what does int temp[256 + 128] = {0}; and temp[+str[i]] = 1; mean [closed]什么 int temp[256 + 128] = {0};和 temp[+str[i]] = 1;意思是[关闭]
【发布时间】:2021-02-27 07:43:16
【问题描述】:

我在谷歌上搜索了一个使用 2 个数组并打印输出而不重复字符的练习,然后我发现了这个更容易阅读和修改的练习,但问题是我不明白 int temp 的含义[256 + 128] = {0};temp[+str[i]] = 1;

这是完整的代码

#include <unistd.h>

void    remove_dup(char *str, char *str2)
{
    int temp[256 + 128] = {0};
    int i;

    i = 0;
    while (str[i])
    {
        if (temp[(int)str[i]] == 0)
        {
            temp[+str[i]] = 1;
            write(1, &str[i], 1);
        }
        i++;
    }
    i = 0;
    while (str2[i])
    {
        if (temp[+str2[i]]  == 0)
        {
            temp[+str2[i]] = 1;
            write(1, &str2[i], 1);
        }
        i++;
    }
}

int main(int argc, char **argv)
{
    if(argc == 3)
        remove_dup(argv[1], argv[2]);
    write(1, "\n", 1);
    return(0);
}

【问题讨论】:

  • 256 + 128 表明代码设计用于签名的charunsigned char,而+str[i]+str2[i] 应该是128+str[i]128+str2[i]

标签: c gcc argc unistd.h


【解决方案1】:

这个:

int temp[256 + 128] = {0};

创建一个大小为 256+128 = 384 的 int 数组,将第一个元素显式初始化为 0,并将其余元素隐式初始化为 0。

还有这个:

temp[+str[i]] = 1;

包含一元 + 运算符的示例,它类似于一元 - 运算符。这个运算符实际上什么都不做,所以这个表达式与:

temp[str[i]] = 1;

它使用str[i] 作为数组temp 的索引并将值1 分配给该元素。

【讨论】:

  • 我很感激,请你运行代码并向我解释如何工作,因为它让我发疯
  • @RyadMney 这是一个单独的问题,而且过于宽泛。
  • 好吧,但我很欣赏你的解释
  • @RyadMney:源代码使用temp来记录一个字符是否被看到,通过在看到值为x的字符时将temp[x]设置为1。每当代码看到以前未见过的字符时,它就会将其写入标准输出。它首先为str 执行此操作,然后为str2 执行此操作。结果是出现在strstr2 中的每个字符都会被写入标准输出一次,无论它出现多少次。
猜你喜欢
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 2022-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
相关资源
最近更新 更多