Re: char *arr[n] Vs. char **arr
- From: "deepak" <deepakpjose@xxxxxxxxx>
- Date: 17 Jul 2006 06:49:23 -0700
yogeshmk wrote:
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[i]=(char*)malloc(strlen(tok))) != NULL)
strcpy(format+i, tok);
}
for (i=1; tok; i++)
{
if ((tok = strtok(NULL, delim)) != NULL)
if((format[i]=(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 -:)
Try this code.
It's just a casual one. I din't freed malloced variable etc.
#include <stdio.h>
#include <string.h>
main(int argc, char *argv[])
{
/* Copy the constant into the memory
* pinted to by 'test_string'
*/
char **test_string;
/* if 'test_string' is declared as below and the program will
give a
* 'Segmentation fault' This is because test_string' is
pointing
* to a constant i.e. somethin that cant be changed.
char *test_string="string to split up"; */
char *sub_string;
int i=0;
/* Extract first string */
test_string = (char **) malloc (sizeof(char *) * 10);
if ((sub_string = strtok(argv[1], "a")) != NULL){
*(test_string + i) = (char *) malloc (strlen(sub_string) + 1);
*(test_string + i) = sub_string;
printf ("%s\n", *test_string);
}
i++;
/* Extract remaining
* strings */
while ( (sub_string=strtok(NULL, "a")) != NULL)
{
*(test_string + i) = (char *) malloc (strlen(sub_string) + 1);
*(test_string + i) = sub_string;
printf("%s\t%s\n", *(test_string + i));
i++;
}
}
~yogesh
.
- Follow-Ups:
- Re: char *arr[n] Vs. char **arr
- From: Barry Schwarz
- Re: char *arr[n] Vs. char **arr
- References:
- char *arr[n] Vs. char **arr
- From: yogeshmk
- char *arr[n] Vs. char **arr
- Prev by Date: Re: char *arr[n] Vs. char **arr
- Next by Date: Re: Windows Coder Needed
- Previous by thread: Re: char *arr[n] Vs. char **arr
- Next by thread: Re: char *arr[n] Vs. char **arr
- Index(es):
Relevant Pages
|