Reputation: 55
I am trying to parse a c char array. It is for class so I have to use c. I am having problems splitting the tokens
I need to be able to accept two different parameters in the following formats: [1234] or [1234 abcd]
When I parse the "[1234 abcd]" I have no issues. But, when I try parsing "[1234]" I get a "no match" error. Although, when I try "[1234 ]" I have no issues.
Can anyone tell me why this would be the case?
Below is my test code:
$ ./parsemem
Splitting string "[1234 abcd]" into tokens:
ip1:1234, ip2:abcd
var1:1234, var2:abcd
parsemem.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//int parse()
int parse(char *str, char *v1, char *v2)
{
char string[11];
strcpy(string,str);
char * pch;
char ip[1][5];
int i=0;
printf ("Splitting string \"%s\" into tokens:\n",string);
pch = strtok (string," []");
while (pch != NULL)
{
strcpy(ip[i],pch);
pch = strtok (NULL, " []");
i++;
}
printf("ip1:%d, ip2:%s\n", atoi(ip[0]), ip[1]);
strcpy(v1,ip[0]);
strcpy(v2,ip[1]);
return 0;
}
int main()
{
char str[] ="[1234 abcd]";
//char str[] ="[1234]";
//char str[] ="[1234 ]";
char var1[5];
char var2[5];
parse(str,var1,var2);
printf("var1:%d, var2:%s\n", atoi(var1), var2);
}
@AndreyT
I am having a similar problem again. When I tried to integrate this into my program using [1234] as an argument I am getting “No match.” Although if I put a space before the ] like [1234 ] There is no problem with strtok.
Having the ] at the end of my string I want to tokenize is a problem. Any ideas why this is the case?
$./parsemem [1234]
./parsemem: No match.
$./parsemem [1234 ]
Splitting string " [1234" into tokens:
ip1:1234, ip2:
var1:1234, var2:
Upvotes: 1
Views: 8396
Reputation: 320541
String "[1234 abcd]"
requires a char array of size 12 (at least). Inside parse
you are copying it into an array of size 11. Why?
Also, your ip
array is declared with first size 1
, which means that it is illegal to access ip[1]
. You can only access ip[0]
.
In other words, your code is hopelessly overrunning array memory in several places. The behavior is undefined. Until you fix the above errors (and any other errors of that nature), any questions about the run-time behavior of your code make no sense at all.
Upvotes: 5