为了学习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
我看不出哪些类型不兼容?我是否意外地返回、调用或错误输入了我不想要的类型?
是的,我知道我的随机性不是很随机,也许有更好的方法来处理这一部分,但这超出了这个问题的范围。