Passing stack string/array to a function

Viewed 39

I split a string by

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

void main()
{
  for (int i = 0; i < 1000; i++)
  {
    char *str, *delm;
    str = "The first part/the second part/still in the second part"; // str comes from within the loop
    delm = "/";

    // The function block
    size_t len = strlen(str);

    char *ptr;
    int pos;
    ptr = strstr(str, delm);
    if (ptr == NULL)
    {
      pos = -1;
    }
    else
    {
      pos = ptr - str;
    }

    if (pos > -1)
    {
      char first[pos + 1];
      strncpy(first, str, pos);
      first[pos] = 0;

      char second[len - pos + 1];
      strncpy(second, str + pos + 1, len - pos);
      second[len - pos] = 0;

      // end of the block

      printf("%s - %s\n", first, second);
    }
  }
}

Since I often use this process, it is beneficial to define a function to make the code easy to read:

void split(const char *str, const char *delm, char *first, char *second){

// the code

}

In this case, I need to define the variables first and second dynamically via malloc and realloc since their sizes are not known outside the function. This may impact the performance (though the function may also do).

In general, I am curious if there is a trick for executing a function with output on the stack?

1 Answers

It seems that the sub-strings only need to be printed.
If that is the case, the precision field can be use to print a specific number of characters.

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

int main ( void)
{
    char *str, *delm;
    str = "The first part/the second part/still in the second part"; // str comes from within the loop
    delm = "/";
    char *find = str;
    char *locate = str;
    int found = 0;
    size_t len = strlen ( delm);

    while ( ( find = strstr ( locate, delm))) {
        int span = (int)( find - locate);
        if ( found) {
            printf ( " - ");
        }
        printf ( "%.*s", span, locate);
        locate = find + len;
        found = 1;
    }
    printf ( "\n");
}
Related