How to resolve “conflicting types error” in C?

后端 未结 7 641
情话喂你
情话喂你 2021-01-27 16:33

For the following C code (for swapping two numbers) I am getting the \"conflicting types\" error for swap function:

#include 
#includ         


        
7条回答
  •  旧时难觅i
    2021-01-27 16:57

    The problem is that swap was not declared before it is used. Thus it is assigned a "default signature", one which will in this case not match its actual signature. Quote Andrey T:

    The arguments are passed through a set of strictly defined conversions. int * pointers will be passed as int * pointers, for example. In other words, the parameter types are temporarily "deduced" from argument types. Only the return type is assumed to be int.

    Aside from that, your code produces a bunch of other warnings. If using gcc, compile with -Wall -pedantic (or even with -Wextra), and be sure to fix each warning before continuing to program additional functionality. Also, you may want to tell the compiler whether you are writing ANSI C (-ansi) or C99 (-std=c99).

    Some remarks:

    • Put spaces after commas.
    • Make main return an int.
      • And make it return 0 or return EXIT_SUCCESS.
    • Import the definition of getch: #include .
      • Or just use getchar.
    • Import the definition of memcpy: #include .
    • Don't return something in a void function.
    • You may want to use malloc to allocate a buffer of variable size. That will also work with older compilers:

      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);
      }
      

提交回复
热议问题