兩個*及p++的另一個意思,
int main(){
char *list[] = {"first", "second", "third", NULL};
for (char **p=list; *p != NULL; p++){
printf("%s\n", p[0]);
}
}
c語言基本型別沒有string, string是多個char, 字串的陣列,用**來代表,
在這裏p++ , 聰明的編譯器會理解成下一個(next),
當然也可以用一個巨集,把*char 替換成string,
typedef char* string;
int main(){
string list[] = {"first", "second", "third", NULL};
for (string *p=list; *p != NULL; p++){
printf("%s\n", *p);
}
}
這樣**就變成* 了,而*p 是p[0]的意思。
覺得這個小巨集,把*char換成string,非常實用,而且比較符合流行的語言。
書中也提及到一些可以省略的c語法。或是較清楚的寫法,
如
if (x > 0)
{
return 1;
}
可寫成
if (x > 0) return 1;
同樣的
int main(){
char *head;
int i;
double ratio, denom;
denom=7;
head = "There is a cycle to things divided by seven.";
printf("%s\n", head);
for (i=1; i<= 6; i++){
ratio = i/denom;
printf("%g\n", ratio);
}
}
可把宣告和給值放一行。
int main(){
double denom = 7;
char *head = "There is a cycle to things divided by seven.";
printf("%s\n", head);
for (int i=1; i<= 6; i++){
double ratio = i/denom;
printf("%g\n", ratio);
}