下面的代码是颠倒字符串中单词的顺序。但是我收到反向功能的“冲突类型”错误。
我对编译器'expected'struct word *'给出的错误感到困惑,但参数的类型是'struct word *'。
我已经在 main 函数之前完成了 rev 函数的声明。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char* rev(char*,struct word*);
int countWord(char*);
struct word{
char word[20];
};
int main(){
char str[100];
char* strp = str;
char result[100];
printf("\nEnter string: ");
fgets(strp,100,stdin);
int noWords = countWord(strp);
struct word *ptr;
ptr = (struct word*)calloc(noWords,sizeof(struct word));
strcpy(result,rev(strp,ptr));
printf("reverse is: %s",result);
return 0;
}
int countWord(char* str){
int count=0;
char str1[100];
strcpy(str1,str);
int i=0;
while(str1[i]!='\0'){
if(str1[i]==' ' && str1[i+1]!=' '){
count++;
}
}
count+=1;
return count;
}
char* rev(char* strp,struct word *ptr){
char str[100];
strcpy(str,strp);
char temp[20];
int i=0,j=0,k=0,l=0;
while(str[i]!='\0'){
j=0;
while(str[i]!=' ' && str[i]!='\0'){
temp[j]=str[i];
i++;j++;
}
if(str[i]==' ')
i++;
temp[j]='\0';
strcpy(ptr[k].word,temp);
k++;
}
char* ret = (char*)malloc(strlen(str)+1);
//ret[l]='\0';
k--;
while(k){
strcat(ret,ptr[k].word);
strcat(ret," ");
k--;
}
return (char*)ret;
}
预期的结果是字符串的单词顺序相反。
Errors and warnings by compiler-
wordRev.c:5:24: warning: ‘struct word’ declared inside parameter list will not be visible outside of this definition or declaration
char* rev(char*,struct word*);
^~~~
wordRev.c: In function ‘main’:
wordRev.c:26:25: warning: passing argument 2 of ‘rev’ from incompatible pointer type [-Wincompatible-pointer-types]
strcpy(result,rev(strp,ptr));
^~~
wordRev.c:5:7: note: expected ‘struct word *’ but argument is of type ‘struct word *’
char* rev(char*,struct word*);
^~~
wordRev.c: At top level:
wordRev.c:47:7: error: conflicting types for ‘rev’
char* rev(char* strp,struct word *ptr){
^~~
wordRev.c:5:7: note: previous declaration of ‘rev’ was here
char* rev(char*,struct word*);