I'm trying to build a function that takes in a c-string and a pointer to an array of character pointers and should return the number of tokens found while putting each token into an array of pointers to character pointers. For example if I pass in the string ls -l file
, it should put into a an array of c-strings that has each word in a line (args[1] = "I\0", args[2] = "am\0", args[3] = "the\0", args[4] = "test\0", args[5] = "string\0"
). Thanks for any help!
Here's what I have so far, but I am getting memory access violations:
#include <iostream>
using namespace std;
int MakeArg(char [], char** []);
int main()
{
char str[] = "I am the test string";
char** argv;
int argc;
argc = MakeArg(str, &argv);
cin.ignore();
cout << "\nPress enter to quit.";
cin.ignore();
return 0;
}
int MakeArg(char s[], char** args[])
{
int word = 1;
for (int i = 0; s[i] != '\0'; i++) //iterates through every character in s
{
*args[word][i] = s[i]; //adds each character to word
if (s[i] == ' ') //when a space is found
{
*args[word][i] = '\0'; //it replaces it with a nullbyte in args
word++; //and moves on to the next word
}
}
return word; //returns number of words
}