If I have:
char *tokenPtr = "testingpointerindex"
and I want to access everything after the 4th character, how would I go about that? I tried :
char *tokenPtr = "testingpointerindex";
char *host = tokenPtr + 4;
printf("%s\n",host);
return host;
It’s just an outake but I hope it gives enough info, I get a bus error.
Thanks
EDIT:
The full code
char * getHost(char *buf){
char *tokenPtr;
tokenPtr = strtok(buf, "\r\n" );
printf("got token\n");
while ( tokenPtr != NULL ) {
if(strncmp(tokenPtr,"Host",4) == 0){
break;
}
else{
tokenPtr = strtok( NULL, "\r\n" );
}
}
char *host = tokenPtr + 7;
printf("%s\n",host);
return host;
}
int main(int argc, char *argv[])
{
char *msg = "GET /index.html HTTP/1.1\r\n Host: www.google.com\r\n\r\n";
getHost(msg);
}
The above code works fine.
However, there’s one thing to mention: string literals (e.g.
"testingpointerindex") are non-modifiable in C. Therefore you should useconst char *, notchar *.