如何用二级指针改写?
#include<stdio.h>
#include<stdlib.h>
int main(void){
char *color[5]={"red","blue","yellow","black","green"},*str;
int i;
str=(char *)calloc(10,sizeof(char));
printf("Enter color: ");
scanf("%s",str);
for(i=0;i<5;i++){
if(strcmp(str,color[i])==0){
break;
}
}
if(i==5)
printf("Not found");
else
printf("%d is %s",i+1,str);
return 0;
}
--------------------------------------------
改写哪有问题?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void){
char **color={"red","blue","green","black","yellow"},*str;
int i;
str=(char *)calloc(10,sizeof(char));
printf("Enter color: ");
scanf("%s",str);
for(i=0;i<5;i++){
if(strcmp(str,*(color+i))==0){
printf("%d is %s",i+1,str);
break;
}
}
if(i==5)
printf("Not found");
free(str);
return 0;
}
c语言不支持二级指针的直接初始化的,也就是你肯定不能用
char **color={"red","blue","green","black","yellow"};
(语法上只是警告,但结果完全不对的)
正确的做法(像你的程序用二级指针是多此一举的)