The following is a snippet of code that parses tokens and stores them. The code compiles and works.
Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int storeTokens(char *src, char *delim, char **storage, size_t len) {
int idx = 0;
char str[100] = {0};
char *token = NULL;
char *saveptr = NULL;
// copy string so we don't modify the source
if (snprintf(str, sizeof(str), "%s", src) < 0) {
return 0;
}
// Loop through string and parse out tokens
token = strtok_r(str, delim, &saveptr);
while ((token != NULL) && (idx < len)) {
snprintf(storage[idx], sizeof(storage[idx]), "%s", token);
strcpy(storage[idx++], token);
token = strtok_r(NULL, delim, &saveptr);
}
// Print the tokens
int i = 0;
for (i = 0; i < idx; i++) {
printf("fun: %s\n", storage[i]);
}
return idx; // number of tokens found
}
int main() {
int i = 0;
char teststr[] = "This*is*my*string*.";
char *storageptr[72];
char storage[72][255];
// Assign storage space to the pointers
for (i = 0; i < 72; i++) {
storageptr[i] = storage[i];
}
// Parse the tokens
int numtokens = storeTokens(teststr, "*", storageptr, 72);
// Print the tokens
for (i = 0; i < numtokens; i++) {
printf("storage: %s\n", storage[i]);
}
return EXIT_SUCCESS;
}
Output
fun: This
fun: is
fun: my
fun: string
fun: .
storage: This
storage: is
storage: my
storage: string
storage: .
The function stores the string with the char **storage variable. The reason for this being a double pointer is so the function can be used on any storage regardless of the length.
My problem is passing the storage into the function. As you can see in main, I created storageptr to point to storage before passing it to the function.
This seems convoluted and unnecessary. Not to mention the time wasted looping and linking each string. However I can't figure out how to pass storage directly into the function without creating storageptr.
I've done reading such as Passing an array of strings to a C function by reference, but nothing really clicks. I can't seem to figure out how to properly pass storage into the function.
char **here: dima.to/blog/?p=478 Its just a list of strings, and its already a pointer so you pass it as is. But, I think what might be causing you problems is finding a distinction between a 2D array and pointers.storeTokensfunction,storageis a pointer to a pointer.storage[idx]is a pointer. And doingsizeofon a pointer (like e.g.sizeof(storage[idx])) returns the size of the pointer and not what it points to. That is seems to work indicates that you're on a 64-bit system where pointers are 64 bits (8 bytes). Try using longer sub-strings than 8 characters and see it fail.malloc,reallocandfree?char storage[72][255]and I'm looking to pass that to a function withchar **storage. The issue I'm having is I can't understand how to pass the 2D array directly into the function without creating pointers to each element.