V
Victor Lagerkvist
Hello, I have the need to parse variable names from a string and save them
somewhere safe for future usage. Here's my first attempt (I don't have any
rules for valid names yet) - but I have a feeling that it's unnecessary
complex? Any input would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int get_ops(char *sen, char ***atom, char limit);
int main(void)
{
char *test = "a, b, c, d"; /* The real input is stripped of spaces */
char **atom;
get_ops(test, &atom, ',');
return 0;
}
int get_ops(char *sen, char ***atom, char limit)
{
int i, j, k;
char **tmp1, *tmp2;
*atom = malloc(sizeof (char *));
**atom = malloc(1);
for (i = j = k = 0; sen != '\0'; ++i) {
if (sen != limit) {
tmp2 = realloc((*atom)[k], j+2);
if (tmp2 == NULL)
return -2;
(*atom)[k] = tmp2;
tmp2 = NULL;
(*atom)[k][j++] = sen;
}
else if (sen == limit) {
(*atom)[k++][j] = '\0';
tmp1 = realloc(*atom, (k +1)*sizeof(char *));
if (tmp1 == NULL)
return -2;
*atom = tmp1;
tmp1 = NULL;
(*atom)[k] = malloc(1);
j = 0;
}
}
return 0;
}
somewhere safe for future usage. Here's my first attempt (I don't have any
rules for valid names yet) - but I have a feeling that it's unnecessary
complex? Any input would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int get_ops(char *sen, char ***atom, char limit);
int main(void)
{
char *test = "a, b, c, d"; /* The real input is stripped of spaces */
char **atom;
get_ops(test, &atom, ',');
return 0;
}
int get_ops(char *sen, char ***atom, char limit)
{
int i, j, k;
char **tmp1, *tmp2;
*atom = malloc(sizeof (char *));
**atom = malloc(1);
for (i = j = k = 0; sen != '\0'; ++i) {
if (sen != limit) {
tmp2 = realloc((*atom)[k], j+2);
if (tmp2 == NULL)
return -2;
(*atom)[k] = tmp2;
tmp2 = NULL;
(*atom)[k][j++] = sen;
}
else if (sen == limit) {
(*atom)[k++][j] = '\0';
tmp1 = realloc(*atom, (k +1)*sizeof(char *));
if (tmp1 == NULL)
return -2;
*atom = tmp1;
tmp1 = NULL;
(*atom)[k] = malloc(1);
j = 0;
}
}
return 0;
}