I'm having issues using malloc to allocate memory using a for loop for a homework assignment. Below is the code for my constructor which takes in a char array and a char pointer array and returns the number of tokens in the char array.
The constructor should go through the char array, skip to the first character that is not empty (the beginning of the first token), then print the index of that char. It should then find the next empty character in the string (the end of the token), and print its index. After doing so, it computes the number of characters in the token and uses malloc to allocate memory in the pointer array. I was told to use memcpy by my professor to copy the token into the pointer array. The program then prints the pointer array. Here is the code
#include <iostream>
using namespace std;
int parseCommandLine(char cline[], char *tklist[])
{
int lineLength = strlen(cline);
int tknCount = 0;
int tknStart;
int tknEnd;
int tknLength;
int tknIndex;
bool check;
cout<<cline<<":"<<lineLength<<endl;
if(cline[0]==0)
{
check = false;
}
else
{
check = true;
}
for(int j=0; j<=lineLength; j++)
{
if (isspace(cline[j]) == false && check==false)
{
cout<<j<<endl;
check = true;
tknStart = j;
}
else if(j==0 && check==true)
{
cout<<j<<endl;
tknStart = j;
}
else if (check==true && (isspace(cline[j]) || j==lineLength))
{
cout<<--j<<endl;
check = false;
tknCount++;
tknIndex = tknCount - 1;
tknEnd = j;
tknLength = tknEnd-tknStart;
tklist[tknIndex] = (char *) malloc(tknLength +1);
memcpy(tklist + tknIndex,cline + tknStart, tknLength);
cout<<tklist<<endl;
}
}
cout<<"There are "<<tknCount<<"tokens in this line.\n"<<endl;
tknCount = 0;
return tknCount;
}
When running the constructor, it is correctly identifying the endpoints of the tokens, but it is printing only the first memory location, which makes it seem as if the malloc is not accepting the loop. It is very strange, please help if you can.
Edit: Here is a simple main()
based on comment:
int main ()
{
char * out[6] = {0};
char cline[] = "new_sensor_node SN42 42 3.57 5.0 7";
parseCommandLine(cline, out);
return 0;
}
Here is the output of running this:
$ ./a.out
new_sensor_node SN42 42 3.57 5.0 7:34
0
14
0x7fffd3762c70
16
19
0x7fffd3762c70
21
22
0x7fffd3762c70
24
27
0x7fffd3762c70
29
31
0x7fffd3762c70
33
33
0x7fffd3762c70
34
There are 6tokens in this line.
Note that the same address is printed for each iteration.
As requested, here is the input code
ifstream infile;
char line[MAX_CMD_LINE_LENGTH] = {0};
char *tokenList[MAX_TOKENS_ON_A_LINE];
int main()
{
infile.open("p4input.txt", ios::in);
if(infile.fail())
{
cout<<"The input file has failed to open. Program will now terminate."<<endl;
return 0;
}
else
{
infile.getline(line,MAX_CMD_LINE_LENGTH);
parseCommandLine(line, tokenList);
system("pause");
return 0;
}
}
In headers
#define MAX_CMD_LINE_LENGTH 256
#define MAX_TOKENS_ON_A_LINE 30