Hi, I need help with this, I'm reading a txt file that has this format:
So far, I read the file using fopen ().Also, I used strtok () to split the string into tokens, but i don't know how store the tokens into an array.
any ideas?

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

int main()
   FILE * pFile;
   char mystring [100];
   char * datos; 
   pFile = fopen ("intermemory.txt" , "r");
   if ( fgets (mystring , 100 , pFile) != NULL )
     puts (mystring);
     fclose (pFile);
   //printf ("\nSplitting string \"%s\" into tokens:\n",mystring);
   datos = strtok (mystring,",");
   while (datos != NULL)
    printf ("%s\n",datos);
    datos = strtok (NULL, ",");
   return 0;

The tokens are char*, right?
All you need is an array of char* of the size you need.
Keep a counter as an offset and increment it on each loop.

Are you keeping all of them?
How many pointers/tokens do you need?

Since you are not likely to know the size of the array, you will need to allocate memory dynamically. To answer your question, an advanced knowledge of pointers is required.

Since neither the size of array, nor the length of each element is known, you will need to allocate a char** (pointer to pointer to char). The first pointer indicates the variable length of the element you want to add to the array, e.g. "1", "12", "256", etc. The second pointer indicates how many elements are in the array (1, 2, 3, ...).

You will need two functions:

  1. One which will dynamically add elements to a C-type string array (char **).
  2. One which will free memory allocated by the first function.

Your function prototypes should have signatures like this:

void create_string_array(char *pString, char ***pppStrings, int *pNumStrings);
void free_string_array(char ***pppStrings, int *pNumStrings);

Now it's up to you to write the code for those functions. :icon_wink:

This article has been dead for over six months. Start a new discussion instead.