冲突类型错误 [英] Conflicting Types Error
问题描述
当我运行以下代码时,出现错误
when i run the following code, i get the error
problem1.c:136:6: error: conflicting types for 'strcspn'
int strcspn( char * str, char * reject )
我不知道为什么会出现冲突类型错误.这是代码:
I'm not sure why I am getting the conflicting types error. here is the code:
int strcspn( char * str, char * reject )
{
int counter = 0;
for (int i = 0; i < strlen(str); i ++)
{ for (int j = 0; j < strlen(reject); j++)
if ( *(str + i) == *(reject + j) )
return counter;
counter++;
}
return counter;
}
void main ()
{
char * str1 = (char *)malloc(sizeof(char)*100);
char * str2 = (char *)malloc(sizeof(char)*100);
sprintf(str1, "abc123");
sprintf(str2, "d2");
printf("%d\n", strcspn(str1, str2));
}
推荐答案
正如 lowtech 在他的回答中已经说过的,你应该避免在你的 C 程序中重新定义已经被采用的函数的名称.
As lowtech already said in his answer, you should avoid to redefine names of the functions in your C programs that are already taken.
无论如何,您的程序存在一些您应该知道的问题.
Any way there are some issue with your program which you should know.
1) strlen 的返回类型是 size_t 而不是 int.
2)主要至少应该是 int main(void){}
3)没有必要投malloc,它的返回类型是void*
4)最重要的是,你应该总是释放你 malloc 的东西.
1) strlen's return type is size_t and not int.
2) main should be at least int main(void){}
3) there is no need to cast malloc, its return type is void*
4) and most important one, you should always free what you malloc.
看看这里:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int strcspn_ss( char * str, char * reject ){
int counter = 0;
size_t i,j;
for (i = 0; i < strlen(str); i ++){
for (j = 0; j < strlen(reject); j++)
if ( *(str + i) == *(reject + j) )
return counter;
counter++;
}
return counter;
}
int main (void){
char * str1 = malloc(sizeof(char)*100);
char * str2 = malloc(sizeof(char)*100);
sprintf(str1, "abc123");
sprintf(str2, "d2");
printf("%d\n", strcspn_ss(str1, str2));
free(str1);
free(str2);
return 0;
}
就像 cad 在他的评论中所说的,有一个重要的事情你应该知道,如果你在函数内部声明一个变量或用作参数不会影响函数 strcspn,请参阅以下内容:
like cad said in his comment, there is an Important thing which you should know, that if you declare a variable inside a Function or used as parameter doesn't affect the function strcspn, please see the following:
#include<stdio.h>
void foo(int strcspn){
printf("strcspn = %d\n",strcspn);
}
int main (void){
int strcspn = 10;
foo(strcspn);
return 0;
}
这是合法的.
这篇关于冲突类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!