对于以下C代码(用于交换两个数字),我得到swap
函数的"冲突类型"错误.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b;
printf("enter the numbers to be swapped");
scanf("%d%d",&a,&b);
printf("before swap");
printf("a=%d,b=%d",a,b);
swap(&a,&b,sizeof(int));
printf("after swap");
printf("a=%d,b=%d",a,b);
getch();
}
void swap(void *p1,void *p2,int size)
{
char buffer[size];
memcpy(buffer,p1,size);
memcpy(p1,p2,size);
memcpy(p2,buffer,size);
return(0);
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以告诉为什么会出现错误?
那是什么解决方案?
Ste*_*202 15
问题是swap
在使用之前没有声明.因此,它被分配了一个"默认签名",在这种情况下,它将与其实际签名不匹配.引用安德烈T:
参数通过一组严格定义的转换传递. 例如,
int *
指针将作为int *
指针传递.换句话说,参数类型是从参数类型临时"推导出来的".仅假定返回类型int
.
除此之外,您的代码会产生许多其他警告.如果使用gcc
,编译-Wall -pedantic
(甚至使用-Wextra
),并确保在继续编写其他功能之前修复每个警告.此外,您可能想告诉编译器您是在编写ANSI C(-ansi
)还是C99(-std=c99
).
一些评论:
main
返回int
.
return 0
或return EXIT_SUCCESS
.getch
:#include <curses.h>
.
getchar
.memcpy
:#include <string.h>
.void
函数中返回某些内容.您可能希望使用malloc
分配可变大小的缓冲区.这也适用于较旧的编译器:
void swap(void *p1, void *p2, int size) {
void *buffer = malloc(size);
memcpy(buffer, p1, size);
memcpy(p1, p2, size);
memcpy(p2, buffer, size);
free(buffer);
}
Run Code Online (Sandbox Code Playgroud)