Y
yogeshmk
I need to break a longer string (with strtok()) and store the smaller
strings in an array. since the number of small strings is not
fixed/known, I cannot use a declaration like char *format[n], so I
declared char** format = NULL;
Now the problem starts. Each time strtok() returns me a token (which is
char*), I call malloc() and I (want to) store the address returned in
the array format[], and copy the token to that address.
code snippet:
------------------
char **format = NULL;
char delim[] = ".-/:";
int i=0;
if ((tok = strtok(argv[1], delim)) != NULL)
{
if((format=(char*)malloc(strlen(tok))) != NULL)
strcpy(format+i, tok);
}
for (i=1; tok; i++)
{
if ((tok = strtok(NULL, delim)) != NULL)
if((format=(char*)malloc(strlen(tok))) != NULL)
strcpy(format+i, tok);
}
The malloc statement gives a segfault. In desparation, I have tried
various combinations of lvalue in malloc, but none of them were correct
(either I get a compiler warning like "invalid lvalue", or "assignment
makes an integer from pointer" etc.. or if compilation is successful,
run always fails with a segfault)
Q: Is above approach fundamentally incorrect? Can I declare something
as a pointer to pointer to char & treat like an array of strings? If
yes, what's wrong in above code? I have no hesitation in admitting that
my pointer fundamentals are not very clear yet -
~yogesh
strings in an array. since the number of small strings is not
fixed/known, I cannot use a declaration like char *format[n], so I
declared char** format = NULL;
Now the problem starts. Each time strtok() returns me a token (which is
char*), I call malloc() and I (want to) store the address returned in
the array format[], and copy the token to that address.
code snippet:
------------------
char **format = NULL;
char delim[] = ".-/:";
int i=0;
if ((tok = strtok(argv[1], delim)) != NULL)
{
if((format=(char*)malloc(strlen(tok))) != NULL)
strcpy(format+i, tok);
}
for (i=1; tok; i++)
{
if ((tok = strtok(NULL, delim)) != NULL)
if((format=(char*)malloc(strlen(tok))) != NULL)
strcpy(format+i, tok);
}
The malloc statement gives a segfault. In desparation, I have tried
various combinations of lvalue in malloc, but none of them were correct
(either I get a compiler warning like "invalid lvalue", or "assignment
makes an integer from pointer" etc.. or if compilation is successful,
run always fails with a segfault)
Q: Is above approach fundamentally incorrect? Can I declare something
as a pointer to pointer to char & treat like an array of strings? If
yes, what's wrong in above code? I have no hesitation in admitting that
my pointer fundamentals are not very clear yet -
~yogesh