I don’t understand why in the url_split function I can use a++, but in the main function I can’t use key_value++, they have the same type…
void url_split(char *src, char **host, char *a[])
{
char const *p1 = "?";
char const *p2 = "&";
*host = strtok(src, p1);
char *str;
while((str = strtok(NULL, p2)))
{
*a = str;
a++;
}
*a = str;
}
int main(int argc, char *argv[])
{
char *host;
char *key_value[100];
char url[] = "http://www.baidu.com/s?wd=linux&cl=3";
url_split(url, &host, key_value);
printf("host = %s\n", host);
while(*key_value)
{
printf("key-value : %s\n", *key_value);
key_value++;
}
return 0;
}
They actually don’t have the same type:
key_valueis of typechar *[100], an array of 100charpointers.ais actually of typechar **, a pointer to achar*, not an array.When you pass
key_valuetourl_splitit decays to achar**, which is whykey_valueis a valid argument to the function and why you usechar**as the type of a function argument that is intended to be an array ofchar*.The post-increment operator is incompatible with arrays, an array can’t be assigned a new value, but it works perfectly fine for pointers, since they can be assigned a new value. That’s why
a++is valid andkey_value++is not.