r/C_Programming • • Oct 21 '26

Question Help With 'String to Token' Parsing Assignment

I was given an assignment for a class I am in and it is expected to be entirely in C code (despite most of us in the class having never been taught how to code with C). I have been attempting to find youtube tutorials and websites, but not much is helping for the assignment itself. The assignment is due in two days.

If there is someone who could help explain to me how I should complete it, or what guides I could look at to help me code it, I would greatly appreciate it. I don't expect (nor want) anyone to do the work for me, I just would like some guidance. I know that many people say to just use AI, but I prefer to avoid using it completely.

---
This is a slightly summarized version of what the assignment says:

Write a function, in C, that will parse a string into tokens (or words), similar to what the shell is required to do.

For this assignment, you are to write a function with the following prototype:

int makearg(char *s, char ***args);
or
int makearg(char s[], char **args[]);
(Correct prototype—don’t change)

This function should accept a (C-type) string and a pointer to a pointer to char (or, if you prefer, a pointer to an array of pointers to char) (i.e., a pointer to the same type as argv in a C program), and should return the pointer defined to point to an array pointing to the separate tokens on the command line, as well as the number of tokens found as the function return value. If some problem occurred during the operation of the function, the value returned should be -1.

No C library string functions may be used, e.g., strlen(), strcat(), strtok(), etc.

The important part of this exercise is the function you write. However, for consistency in grading, the main program should be written to input a line, call the function, then print out the number of arguments found, and finally, display the arguments, one per line. Note that, the value of the pointer argument is undefined when it is passed to the makearg() function. makearg() must allocate any necessary dynamic memory necessary for use by the program. (The array used for the unparsed string need not be dynamically allocated.)
strtok() may not be used for parsing.

Deliverables:
A program design sheet. Describe all functions needed to implement your program.
Programming Log:
– Record the time required to design and implement your program.
– Record of things you encountered/learned while implementing your program.
Output—proof that your program worked.
Program—fully documented.

---

Again, I don't necessarily want someone to do all the code for me, but giving me any advice/guidance on what I can do or where I can find resources to help, I would greatly appreciate it.

14 Upvotes

24 comments sorted by

6

u/flyingron Oct 21 '26

Your description of your function siguatures are incorrect.

(or, if you prefer, a pointer to an array of pointers to char) 

No, char**[] is an array of pointers to pointers to char. As far as parameter typing is concerned, it is identical to char***..

1

u/Kit_Le_Trash Oct 21 '26

I apologize that it isn't right. It was what was provided to me in the assignment.

3

u/Plus-Dust Oct 21 '26

Fwiw that prototype is terrible, char ***? Really? And no const on the input? In a real program we would probably have a Token struct and a dynamic list struct, and point the parser at a list to fill with tokens, just saying. I'd never merge code that used insanity like triple char pointers if I could help it.

Just iterate over the chars one at a time with a for or while loop that stops on the null char. If char is not a space, add it to a buffer like buffer[outsize++] = ch; but if its a space, write 0 to null terminate the buffer then add it to the list.

1

u/Kit_Le_Trash Oct 21 '26

I apologize that the prototype is bad. It is what was given to me on the assignment.

Thanks for the help.

2

u/dvhh Oct 21 '26

Obviously a pointer to an array of char array, as no size is passed I assume that the array is either large enough, or allocated by the function when NULL

2

u/SmokeMuch7356 Oct 21 '26

It's pretty obvious from the prototype that they're meant to allocate it:

char **args = NULL;
int numargs = makearg( str, &args );

7

u/Stickhtot Oct 21 '26

For a start, iterate on the input to be tokenized until you hit \0

6

u/Stickhtot Oct 21 '26

Then decide on your delimiter(s), and put them on a variable

1

u/Kit_Le_Trash Oct 21 '26

Okay, thank you. I'll definitely try that.

0

u/Total-Box-5169 Oct 21 '26

This should be implemented as a generator of string views to decouple token parsing logic from memory management logic, and allow to pick the data structure that is more convenient to store the tokens if such a thing is even needed depending on each use case.

2

u/Kit_Le_Trash Oct 21 '26

Thank you. This helps a lot.

0

u/FransFaase Oct 21 '26

You have to iterate twice over the string in 's'. First to determine the number of arguments. If you know the number of arguments you have to allocate memory using the malloc function. If the malloc function returns 0, let the function return -1. (I would use a local variable declaration of type 'char *results[]' and only at the end assign it to 'args'.) Now it is time to iterate for the second time. For each argument, first determine the length, call malloc again with the size of the argument plus one. Copy the characters of the argument into the allocated string. You could also ask some AI and try to understand the resulted code and fix any bugs. Or use it to generate code for 'iterate string in C'.

2

u/Kit_Le_Trash Oct 21 '26

I appreciate the help. I know that AI is an option, however, I prefer to avoid using it.

1

u/FedUp233 Oct 21 '26

You didn’t really describe the parsing required. If it’s just breaking at spaces, you can actually do it in place in the original array by just skipping spaces, put a pointer to the first non-space character into the output pointer array then move forward till you find a space or null. If space, replace that character in the original string with null and repeat.

You didn’t say if it was ok to modify the original string.

You could do a first pass over the string just counting the tokens to get the correct size output pointer array. You might add one more entry as this type of structure is often terminated with a null pointer, though you are apparently returning g the count.

Just something to think about.

1

u/Educational-Paper-75 Oct 22 '26

Typically tokens have start and/or end characters and/or allowed or unallowed continuation characters. You could build a table of allowed token transitions.

0

u/SmokeMuch7356 Oct 21 '26 edited Oct 21 '26

Honestly, the tokenizing is going to be the easy part; building the output array is what's gonna be the pain in the ass.

I'm assuming this is just breaking up a string based on some set of delimiters (not actual token parsing that distinguishes between identifiers, numeric literals, string literals, punctuators, etc.). And, based on the provided prototype, the delimiters are going to be hardcoded (boo). So that likely means any whitespace character (blank, tab, newline, etc.).

So the heart of your tokenizing function will use two variables, one that points at the first character of a token and one that points to the last. Set both to the first character of the input string, then advance the end pointer until you find the delimiter.1 You'll use the difference between the two to size your destination buffer, allocate it, and then copy the token to that new buffer. Find the next non-delimiter character in the input string, set both your start and end variables to point to it, repeat until you reach the end of the string.

Again, that's the easy part. You should be able to bang that out pretty quickly.

It's building the output argument array that's gonna be fun. That's ultimately gonna look something like this:

                This is storage for pointers to
                each token buffer; since you don't
                know how many tokens you're going
                to have, you will have to allocate
                this array dynamically.
                  |
                  |
                  v
      +---+     +---+                      +---+---+---+
args: |   | --> |   | args[0] -----------> |   |   |   |...  <---- This is storage
      +---+     +---+                      +---+---+---+           for the individual
                |   | args[1] ---------+                           tokens; you will
                +---+                  |   +---+---+---+           allocate these
                |   | args[2] -------+ +-> |   |   |   |...  <---- buffers dynamically
                +---+                |     +---+---+---+           and each element of
                 ...                 |                             args will store the
                +---+                |     +---+---+---+           pointer to each
                |   | args[N-1] --+  +---> |   |   |   |...  <---- buffer.
                +---+             |        +---+---+---+
                                  |
                                  +------> NULL

In the code that calls your function, args will be declared as

char **args;  

Your function will need to modify this pointer value, so the caller will pass a pointer to it:

int num_tokens = makeargs( str, &args );

which is why args is char *** in your prototype.

You will need to allocate space for *args. Remember that the general rule for allocating an array of T is:

T *ptr;
...
ptr = malloc( sizeof *ptr * N ); // sizeof *ptr == sizeof (T)

In you're case, you're not going to be assigning to args, you're going to be assigning to *args; you're updating the pointer in the caller. So in this case you'd write:

*args = malloc( sizeof **args * N );

The type of *args is char **, and the type of **args is char *; IOW, you're allocating an array of char * and assigning the pointer to that array to *args.

Now, the question is what value do you use for N? You don't know how many tokens you will have ahead of time, so how do you decide?

Fortunately, you can resize dynamically-allocated arrays as necessary using the realloc function; the general approach is something like this:

size_t buffer_size = SOME_INITIAL_SIZE;
size_t count = 0;

T *arr = malloc( sizeof *arr * buffer_size );
while ( more_data )
{
  /**
   * Have we hit the end of our buffer?
   */
  if ( count == buffer_size )
  {
    /**
     * Yes.  Double the size of the buffer using realloc.
     */
    T *tmp = realloc( arr, sizeof *arr * (buffer_size * 2) ); 
    if ( tmp )
    {
      arr = tmp;
      buffer_size *= 2;
    }
    else
    {
      /**
       * The realloc call failed, leaving the original array in place.
       * You can treat this as a fatal error, or you can proceed
       * with the data you already have.  For this example, we'll treat
       * it as a fatal error and release any memory we've allocated
       * so far.
       */
      free( arr );
      return some_failure_code;
  }
  arr[count++] = next_data_item;
}

This way you can process your string in one pass. Pick a value for SOME_INITIAL_SIZE that covers most reasonable use cases (8, 16, whatever) so you won't have to resize except in unusual circumstances.

What throws a tiny monkey wrench into this is the type of args. When you write to an element of args, you'll need dereference args before indexing into it:

(*args)[i] = some_pointer_to_char;

We're not indexing into args, where indexing into what args points to.

So, the operations your code will need to perform:

  • Allocate space for the args array;
  • Find the next token in the string (using the method I described above);
  • Allocate storage for that token (remembering to allocate an extra element for the 0 terminator);
  • Copy the token to that new storage (remembering to terminate the string);
  • Assign the pointer to that storage to the next available element of args;
  • Resize args as necessary;
  • Repeat until you're out of input;

For your sanity I'd recommend breaking as many of these operations out into separate functions as possible.


  1. These don't have to be actual pointers, they can just be size_t variables that store array indices. Although using pointers will make some parts of this easier.

Hi downvoter! Care to tell me how to improve my answer?

1

u/Kit_Le_Trash Oct 21 '26

That's a lot of information. Thank you.

1

u/SmokeMuch7356 Oct 22 '26

You are welcome. I can be a windy bastard, but hopefully some of that will be useful.

-1

u/[deleted] Oct 21 '26

[removed] — view removed comment

1

u/Kit_Le_Trash Oct 21 '26

Awesome, thank you. I really appreciate it. I'll try to do that.

2

u/smichaele Oct 21 '26

Per the requirements “No C library string functions may be used, e.g., strlen(), strcat(), strtok(), etc.”

2

u/tharold Oct 21 '26

Presumably it would be ok to write one's own my_strncmp. I would probably do this for strtok, except strtok is such an abomination.