C
cong10
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int str_to_argv(char *str, int *argc, char **argv)
{
char *tmpstr;
char *token;
int token_count = 0;
int i;
printf("argv %p\t*argv %p\n", argv, *argv);
//get how many token
tmpstr = strdup(str);
token = strtok(tmpstr, " ");
while(1){
if(token != NULL){
token_count ++;
}
else{
break;
}
token = strtok(NULL, " ");
}
*argc = token_count;
//make sure argument are not more than 20 character, else likely
will core dump
argv = (char **) calloc(1, token_count * 20 * sizeof(char));
tmpstr = strdup(str);
token = strtok(tmpstr, " ");
argv[0] = token;
printf("token = %s\n", argv[0]);
i = 1;
while(i != token_count){
token = strtok(NULL, " ");
argv = token;
printf("token = %s\n", argv);
i++;
}
return 0;
}
int main(int argc, char *argv[])
{
int c;
char **v;
int i;
str_to_argv("na ru wa", &c, v);
printf("c = %d\n", c);
i = 0;
while(i != c){
printf("argv[%d] = %s\n", i, v);
i++;
}
free(v);
return 0;
}
====================
Problem:
====================
Segmentation fault when printf("argv[%d] = %s\n", i, v);
the v pointed change in str_to_argv function which malloc,
but when return back to main... it seems like not getting the new
address..
anyone can help?
====================
#include <string.h>
#include <stdlib.h>
int str_to_argv(char *str, int *argc, char **argv)
{
char *tmpstr;
char *token;
int token_count = 0;
int i;
printf("argv %p\t*argv %p\n", argv, *argv);
//get how many token
tmpstr = strdup(str);
token = strtok(tmpstr, " ");
while(1){
if(token != NULL){
token_count ++;
}
else{
break;
}
token = strtok(NULL, " ");
}
*argc = token_count;
//make sure argument are not more than 20 character, else likely
will core dump
argv = (char **) calloc(1, token_count * 20 * sizeof(char));
tmpstr = strdup(str);
token = strtok(tmpstr, " ");
argv[0] = token;
printf("token = %s\n", argv[0]);
i = 1;
while(i != token_count){
token = strtok(NULL, " ");
argv = token;
printf("token = %s\n", argv);
i++;
}
return 0;
}
int main(int argc, char *argv[])
{
int c;
char **v;
int i;
str_to_argv("na ru wa", &c, v);
printf("c = %d\n", c);
i = 0;
while(i != c){
printf("argv[%d] = %s\n", i, v);
i++;
}
free(v);
return 0;
}
====================
Problem:
====================
Segmentation fault when printf("argv[%d] = %s\n", i, v);
the v pointed change in str_to_argv function which malloc,
but when return back to main... it seems like not getting the new
address..
anyone can help?
====================