我对C语言非常陌生,因为我只把它作为一门入门课程,而且我还有一个家庭作业的问题。该程序的目标是将string类型的数组名称和动态选择的字符从循环传递到函数。该函数必须检查字符串中所选的字符,如果找到,则返回指向字符串中该字符的指针。如果找不到该字符,则返回一个空指针。我的代码在字符串的第一个字符上陷入了无限循环...
#include<stdio.h>
char occur(char array[],char c);
int main(void){
char array[]="Hello World!";
int i = 33;
char c;
char occurence;
for(i=33;i<=126;i++){
c = i;
occurence=occur(array,c);
printf("%c\n",occurence);
}
return 0;
}
char occur(char array[], char c){
int i = 0;
char *temp=array;
for(temp=array+i;*temp!='\0';i++){
if(c==array[i]){
return *temp;
}
else{}
}
return 0;
}发布于 2016-04-22 10:37:49
使用
for(temp=array; *temp!='\0'; temp++){
if(c==*temp) {
...发布于 2016-04-22 10:47:27
这样做你的for语句:
for (char* temp = array; *temp != '\0'; temp++) {
if (*temp == c) {
return temp;
}
}然后删除前两行。我会解释你的函数出了什么问题。在这行中:
for(temp=array+i;*temp!='\0';i++){ temp=array+i部件只运行一次,因此即使i更改了temp的值,它也永远不会更改。在我的示例中,第一个temp被设置为array,因此该部分:
... char* temp = array; ...temp指向下一个char each循环:
... temp++ ...如果看到一个空字符,循环就会停止:
... *temp != '\0' ...就是这样!
发布于 2016-04-22 10:49:28
多亏了潘若晨,我的代码现在可以正确运行了。这就是它:
#include<stdio.h>
char occur(char array[],char c);
int main(void){
char array[]="Hello World!";
int i = 33;
char c;
char occurence;
for(i=33;i<=126;i++){
c = i;
occurence=occur(array,c);
if(occurence==0){}
else{
printf("%c\n",occurence);
}}
return 0;
}
char occur(char array[], char c){
char *temp=array;
for(temp=array;*temp!='\0';temp++){
if(c==*temp){
return *temp;
}
else{}
}
return 0;
}https://stackoverflow.com/questions/36783750
复制相似问题