For example:
int main(){
char *str[4];
char data[]="abcd:3:4:5";
str[0]=strtok(data,":");
str[1]=strtok(NULL,":");
str[2]=strtok(NULL,":");
str[3]=strtok(NULL,":");
return 0;
}
On the input "abcd:3:4:5"
, a
is a string and b
c
and d
are integers. When I use strtok() the broken string is stored in 4 pointers (str[0]
to str[3]
), which are immutable. I need to store them in an array where I can change the integers afterwards. I would use atoi()
but i get the error 'warning: assignment makes pointer from integer without a cast'
. I'd like to store a
,b
,c
e d
in a non-pointer array, so I can change them afterwards. How do I convert the from char*
to char
(afterwards I'll just use atoi()
on the strings to get the integers).
To briefly answer your question, the code above should look like this:
char input[] = "abcd:18:04:12";
char* p1 = strtok(input, ":");
char* p2 = strtok(NULL, ":");
char* p3 = strtok(NULL, ":");
char* p4 = strtok(NULL, ":");
int val1 = atoi(p2);
int val2 = atoi(p3);
int val3 = atoi(p4);
// and now you can do something with val1, val2 and val3
Note that strtok will place a '\0'
character wherever it sees one of your tokens. If you intend to use the input
string after, you need a copy of it to pass to strtok.