Do you mean to create an array of indexes to the original string? Or an array of strings? Is your project to tokenize the words in your code? I'll assume all of the above here... This hasn't been compiled or tested
// Function Prototypes (A.K.A. Function Declarations)
int main (void);
int FindNextWord (char* line, int* startIndex);
//---------------------------------------------------------
// Function Definitions
//---------------------------------------------------------
// Note: This function is destructive (it reuses the same memory, it doesn't make copies)
int main(void)
{
#define MAX_WORDS 256
#define MAX_LINE_LENGTH 1024
int lineIndex;
int wordIndex;
int wordLength;
int wordCount;
char* oneWord;
int token;
char codeLine[MAX_LINE_LENGTH];
char* wordStringsArray[MAX_WORDS];
int wordIndexesArray[MAX_WORDS];
// Get the line of code (however you do this)
while (GetNextLine(codeLine))
{
// Separate words
wordCount = 0;
lineIndex = 0;
wordLength = FindNextWord(codeLine, &lineIndex);
while (wordLength)
{
// NULL terminate the word found. Note: This alters the original codeLine string.
codeLine[lineIndex + wordLength] = NULL;
// This literally divides the line string into word strings (same memory)
// Copy the address of the beginning of the word to the Word Strings Array
wordStringsArray[wordCount] = &codeLine[lineIndex];
// Store index to the word found in the index array
wordIndexesArray[wordCount] = lineIndex;
wordCount++;
wordLength = FindNextWord(codeLine, &lineIndex);
}
// To access the word via the Word Indexes Array:
oneWord = codeLine[wordIndexesArray[wordIndex]];
// To access the word via the Word Strings Array:
oneWord = wordStringsArray[wordIndex];
// This or whatever you do with a word once it's found
token = TokenizeWord(oneWord);
// Reloop: Get the next line (until there are no more)
}
// All is well
return (0);
}
//---------------------------------------------------------
// Finds the next word (using spaces)
// Returns length of the word (or 0 if end of line)
// Updates startIndex to be at the beginning of the word (in case of multiple spaces in a row)
int FindNextWord(char* line, int* startIndex)
{
int lineIndex;
int lineLength;
// Find index to the start of the next word
lineIndex = *startIndex;
while ((line[lineIndex] != NULL) && (line[lineIndex] == ' '))
{
lineIndex++;
}
if (line[lineIndex] != NULL)
{
*startIndex = lineIndex;
}
else
{
return (0);
}
// Find index to the end of the word
lineLength = 0;
while ((line[lineIndex] != NULL) && (line[lineIndex] != ' '))
{
lineLength++;
lineIndex++;
}
return (lineLength);
}
//---------------------------------------------------------