Extracting the first two words in a sentence in C without pointers

135 Views Asked by At

I am getting used to writing eBPF code as of now and want to avoid using pointers in my BPF text due to how difficult it is to get a correct output out of it. Using strtok() seems to be out of the question due to all of the example codes requiring pointers. I also want to expand it to CSV files in the future since this is a means of practice for me. I was able to find another user's code here but it gives me an error with the BCC terminal due to the one pointer.

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);
1

There are 1 best solutions below

2
Miguel Sandoval On

Pointers are powerful, and you wont be able to avoid them for very long. The time you invest in learning them is definitively worth it.

Here is an example:

#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;
}

You can easily use the function:

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;
}