"error: conflicting types" when trying to return a character-array reference

"error: conflicting types" when trying to return a character-array reference

为了学习 C 和字符串操作,我正在制作一个小程序,它可以简单地将随机 IP 地址生成为字符串并将其输出。从我从各种教程以及此处关于 Whosebug 的示例中收集到的内容来看,下面是这样做的一种方法,但是 returning 字符数组引用让我很困惑,因为它无法编译:

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

gcc 输出:

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

我看不出哪些类型不兼容?我是否不小心 return、调用或误投了我不想要的类型?

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

  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)
{
     /* ...*/
}