PDA

查看完整版本 : 指標使用的時機?


哈啦
2014-06-25, 03:23 PM
這是書上的範例,用一個字串二維陣列,然後輸入前面的顏色單字,出現後面的顏色意義。程式碼如下:
#include <stdio.h>
#include <string.h>

char *p[][2]={
"red","hot",
"green","peace",
"blue","suck",
"yellow","bright",
"white","pure",
"",""};

int main(void){
int x;
char color[90];
printf("enter a color:\n");
gets(color);
for(x=0;*p[x][0];x++)
{if (!strcmp(p[x][0],color))
printf("%s is %s.",color,p[x][1]);
}
return 0;
}

搞不懂的就是為何前面藍字部份是可以用指標*p[][],而紅字部份則沒有指標*的符號?
我有試著把它們加上指標符號,結果是錯的。那請問一下,後面為何不用指標符號?

thanks

yumi
2014-06-25, 04:04 PM
函数原型:
int strcmp(const char *s1,const char *s2)

strcmp(*p[x][0],color)是不允许的转换

哈啦
2014-06-25, 04:14 PM
函数原型:
int strcmp(const char *s1,const char *s2)

strcmp(*p[x][0],color)是不允许的转换


不太了解?

~what~what

我目前學到的strcmp是strcmp(str_1,str_2);裡面並不是用指標,所以本題的{if (!strcmp(p[x][0],color))其中的p而非*p是因為無法用*而拿掉嗎?
再來就是最後的printf("%s is %s.",color,p[x][1]); 為何不寫成printf("%s is %s.",color,*p[x][1]);呢?
而且我發現在(!strcmp(p[x][0],color)中如果寫成(!strcmp(p[x][0],&color)也是可以的,why?

還有,為何這個char *p[][2]要在int main(void)的外面定義呢?我有試著把它移到main函數裡面來,答案似乎都一樣正確。

yumi
2014-06-25, 05:13 PM
(!strcmp(p[x][0],&color)
color是字符阵列,本身指向字符串起始位置。是否加&都一样的。
就本程式而言,char *p[][2]在int main(void)外边定义和在mian()里面定义是没有区别的,因为只有一个main()函数,只要在使用前定义char* p[][2]即可。
但是,如果程式里有其他函数的话,在main()里定义char *p[][2],其他函数就无法使用char *p[][2]的。

哈啦
2014-06-25, 05:17 PM
(!strcmp(p[x][0],&color)
color是字符阵列,本身指向字符串起始位置。是否加&都一样的。
就本程式而言,char *p[][2]在int main(void)外边定义和在mian()里面定义是没有区别的,因为只有一个main()函数,只要在使用前定义char* p[][2]即可。
但是,如果程式里有其他函数的话,在main()里定义char *p[][2],其他函数就无法使用char *p[][2]的。

感謝,這二點我都瞭解了:bow