代码之家  ›  专栏  ›  技术社区  ›  Jarmund

尝试返回字符数组引用时出现“错误:冲突类型”[重复]

  •  -1
  • Jarmund  · 技术社区  · 4 年前

    为了学习C和字符串操作,我正在制作一个小程序,它可以简单地生成随机IP地址作为字符串并输出。根据我从stackoverflow的各种教程和示例中收集到的信息,下面是一种方法,但返回字符数组引用让我感到困惑,因为它无法编译:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
      char *testip = randip();
      printf("%s", testip);
      free(testip);
      return 0;
    }
    
    // get rand IP
    char* randip()
    {
      char *ip = malloc(16);
      int a = randint(1,254);
      int b = randint(0,254);
      int c = randint(0,254);
      int d = randint(0,254);
    
      sprintf(ip, "%d.%d.%d.%d", a, b, c, d);
      printf("D> randip generated %s", ip);
      return ip;
    }
    
    // generate rand int
    int randint(unsigned int min, unsigned int max)
    {
           double scaled = (double)rand()/RAND_MAX;
           return (max - min +1)*scaled + min;
    }
    

    test.c: In function ‘main’:
    test.c:8:18: warning: initialization makes pointer from integer without a cast [enabled by default]
    test.c: At top level:
    test.c:17:7: error: conflicting types for ‘randip’
    test.c:8:18: note: previous implicit declaration of ‘randip’ was here
    

    我看不出哪些类型不兼容?我是否意外地返回、调用或错误输入了我不想要的类型?

    是的,我知道我的随机性不是很随机,也许有更好的方法来处理这一部分,但这超出了这个问题的范围。

    1 回复  |  直到 4 年前
        1
  •  1
  •   0___________    4 年前
    1. 在调用函数原型之前,您需要它。
    2. 如果函数不接受参数,则将其声明为 char* randip(void)
    3. 使用正确的 main 签名。在这种情况下 int main(void)
    int randint(unsigned int min, unsigned int max);
    char* randip(void);
    
    int main(void)
    {
         /* ...*/
    }
    
    char* randip(void)
    {
         /* ...*/
    }
    
    // generate rand int
    int randint(unsigned int min, unsigned int max)
    {
         /* ...*/
    }