【问题标题】:Extracting the first two words in a sentence in C without pointers在没有指针的情况下提取C中句子中的前两个单词
【发布时间】:2021-08-17 18:28:03
【问题描述】:

到目前为止,我已经习惯于编写 eBPF 代码,并且希望避免在我的 BPF 文本中使用指针,因为从中获得正确的输出非常困难。由于所有示例代码都需要指针,因此使用 strtok() 似乎是不可能的。我还想在将来将其扩展为 CSV 文件,因为这对我来说是一种练习方式。我可以在这里找到另一个用户的代码,但是由于一个指针,它给了我一个 BCC 终端错误。

char str[256];
bpf_probe_read_user(&str, sizeof(str), (void *)PT_REGS_RC(ctx));
char token[] = strtok(str, ",");

char input[] ="first second third forth";
char delimiter[] = " ";
char firstWord, *secondWord, *remainder, *context;

int inputLength = strlen(input);
char *inputCopy = (char*) calloc(inputLength + 1, sizeof(char));
strncpy(inputCopy, input, inputLength);

str = strtok_r (inputCopy, delimiter, &context);
secondWord = strtok_r (NULL, delimiter, &context);
remainder = context;

getchar();
free(inputCopy);

【问题讨论】:

  • 那么你打算用什么来代替指针呢?
  • 是指针还是什么都不是......提供指针基本讨论的一些链接可能会有所帮助。 Difference between char pp and (char) p?Pointer to pointer of structs indexing out of bounds(?)... (忽略标题,答案讨论指针基础知识) 阅读两者你会明白指针只不过是一个普通变量,它保存一个内存地址作为它的值。它们并没有那么复杂......
  • 鉴于C 中的字符串是指向字符的指针,很难想象您将能够避免使用指针。
  • 与其回避指针,不如了解它们的工作原理并接受它们。
  • 我完全可以使用指针,只是 BCC 编译器绝对不喜欢 bpf 文本中的指针。我希望除了使用指针之外还有其他东西,因为我对 C 有点陌生。

标签: c algorithm bcc-bpf


【解决方案1】:

指针很强大,你将无法长时间避免它们。花时间学习它们绝对值得。

这是一个例子:

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

/**
    Extracts the word with the index "n" in the string "str".
    Words are delimited by a blank space or the end of the string.
}*/
char *getWord(char *str, int n)
{
    int words = 0;
    int length = 0;
    int beginIndex = 0;
    int endIndex = 0;
    char currentchar;
    while ((currentchar = str[endIndex++]) != '\0')
    {
        if (currentchar == ' ')
        {
            if (n == words)
                break;
            if (length > 0)
                words++;
            length = 0;
            beginIndex = endIndex;
            continue;
        }
        length++;
    }
    
    if (n == words)
    {
        char *result = malloc(sizeof(char) * length + 1);
        if (result == NULL)
        {
            printf("Error while allocating memory!\n");
            exit(1);
        }
        memcpy(result, str + beginIndex, length);
        result[length] = '\0';
        return result;
    }else
        return NULL;
}

您可以轻松使用该功能:

int main(int argc, char *argv[])
{
    char string[] = "Pointers are cool!";
    char *word = getWord(string, 2);
    printf("The third word is: '%s'\n", word);
    free(word); //Don't forget to de-allocate the memory!
    return 0;
}

【讨论】:

  • 我的帖子应该更清楚,但 BCC 内核根本不喜欢指针。我最初的目标是使用 strtok() 编写代码,但使用它编写 eBPF 代码一直很痛苦。
  • 嗯..你试过我提供的代码了吗?你能告诉我们这个问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
相关资源
最近更新 更多