Hi! I wrote a function which parses a string like this: "str0\\0str1\\0.....strN\\0"
into an array of string like this:
arg[0]="str0"
arg[1]="str1"
.
.
arg[N]="strN"
it works fine,... but when the last string (strN) is not followed by "\\0" it doesn't work!
Code:
char** get_args(char *args, int lim) {
int read=0, i, k=0;
char **tmp;printf("Get args riceve: %s\n", args);
ec_null( (tmp=(char**)malloc(sizeof(char*)*lim)), 0 )
for (i=0; i<=strlen(args); i++) {
if (read>lim) return NULL;
if ((args[i]=='\\' && (!(args+i+1) ||
args[i+1]=='0')) || i==strlen(args)) {
ec_null( (tmp[read]=(char*)malloc(sizeof(char)*(i-k+1))), 0);
snprintf(tmp[read++], i-k+1, "%s", args+k);
k=(++i)+1;
}
}
if (read==lim)
return tmp;
return NULL;
}
The parameter "lim" is an integer that indicates the number of arguments the function has to find, if more or less than lim arguments will be found the function will return NULL to indicate there's an error!
Thanks!