r/C_Programming • u/Kit_Le_Trash • 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.
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***..
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.
7
u/Stickhtot Oct 21 '26
For a start, iterate on the input to be tokenized until you hit \0
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.
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'.
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:
In the code that calls your function,
argswill be declared asYour function will need to modify this pointer value, so the caller will pass a pointer to it:
which is why
argsischar ***in your prototype.You will need to allocate space for
*args. Remember that the general rule for allocating an array ofTis: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:The type of
*argsischar **, and the type of**argsischar *; IOW, you're allocating an array ofchar *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
reallocfunction; the general approach is something like this:This way you can process your string in one pass. Pick a value for
SOME_INITIAL_SIZEthat 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 ofargs, you'll need dereferenceargsbefore indexing into it:We're not indexing into
args, where indexing into whatargspoints to.So, the operations your code will need to perform:
argsarray;args;argsas necessary;For your sanity I'd recommend breaking as many of these operations out into separate functions as possible.
size_tvariables 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/[deleted] Oct 21 '26
[removed] — view removed comment