outsourcing strtok() in function in c -
i want outsource string operation function , ask results in main. doesn't work, , don't understand why.
#include <stdio.h> #include <string.h> void splitrequest(char request[], char method[], char ressource[], char proto[]) { method = strtok(request, " "); ressource = strtok(null, " "); proto = strtok(null, " "); printf("\nresult:\n\nmethod:\t\t%s\nressource:\t%s\nproto:\t\t%s\n",method,ressource,proto); } int main() { char method[50], ressource[50], proto[50], request[50]; memset(method, '\0', 50); memset(ressource, '\0', 50); memset(proto, '\0', 50); memset(request, '\0', 50); strcpy(request,"get /index.htm http/1.1"); //rehash query splitrequest(request, method, ressource, proto); //check results printf("\nresult:\n\nmethod:\t\t%s\nressource:\t%s\nproto:\t\t%s\n",method,ressource,proto); return 0; }
in splitrequest
function arguments pointers. , more importantly local variables. changes them (like making them point anywhere else) affect local variable, nothing else.
the solution copy memory instead. perhaps like
char *temp; if ((temp = strtok(request, " ")) != null) { strcpy(method, temp); } // , on...
a little elaboration mean...
in c function arguments passed by value. means value copied , function have local copy of value. chaning copy of course not change original value.
it same pointers. when call splitrequest
function pointers pass copied. inside function variable method
(for example) pointing memory of array defined in main
function. when assign variable, with
method = strtok(...);
you modify local variable, local copy of pointer. when function returns local variable method
goes out of scope, , changes lost.
there 2 solutions problem. 1 emulate pass reference (something c doesn't have, why must emulated), not work long have array. therefore second , easiest solution: copy memory pointed local variable method
, show above.
an important note though: when call splitrequest
function, passing arrays, arrays not passed. instead arrays decays pointer first element, , inside function variables defined arguments pointers , not arrays.
the call
splitrequest(request, method, ressource, proto);
is equal to
splitrequest(&request[0], &method[0], &ressource[0], &proto[0]);
and function declaration
void splitrequest(char request[], char method[], char ressource[], char proto[])
is equal to
void splitrequest(char *request, char *method, char *ressource, char *proto)
so no strings not copied, pointers. otherwise have gotten error when assigning pointer, since can't assign arrays copy them.
Comments
Post a Comment