gpt4 book ai didi

c - 调用该函数时显示相同的随机数

转载 作者:行者123 更新时间:2023-11-30 19:00:36 24 4
gpt4 key购买 nike

我创建了一个方法,根据生成的随机数的值返回一个字符串。当函数位于调用它的同一程序文件中时,这将按预期工作。

但是当我在新的头文件中定义此方法,然后在不同的文件中调用它时,它会返回相同的随机数。

定义方法:

char* newTrafficGenerator(void)
{
int i;
int count =0;
static char currentTrafficType[6];
i = random_rand();
printf("Current random no is: %d\n",i);
if (i>0 && i<32767)
{
strncpy(currentTrafficType,"Type A",sizeof(currentTrafficType));
}
else if(i>32767 && i<55705)
{
strncpy(currentTrafficType,"Type B",sizeof(currentTrafficType));
}
else
{
strncpy(currentTrafficType,"Type C",sizeof(currentTrafficType));
}
return currentTrafficType;
}

通过以下代码调用:

static void generateInfiniteRandomNumber(void)
{
int count=0;
char *c;
while(count<10)
{
c = newTrafficGenerator();
printf("Type is %s\n",c);
count++;
}
}

在同一文件中调用时的输出为:

Current random no is: 18547
Type is Type A
Current random no is: 56401
Type is Type C
Current random no is: 23807
Type is Type A
Current random no is: 37962
Type is Type B
Current random no is: 22764
Type is Type A
Current random no is: 7977
Type is Type A
Current random no is: 31949
Type is Type A
Current random no is: 22714
Type is Type A
Current random no is: 55211
Type is Type B
Current random no is: 16882
Type is Type A

当在新的头文件中定义并调用时输出为:

Current random no is: 1920540202
Type is Type C
Current random no is: 1920540202
Type is Type C
Current random no is: 1920540202
Type is Type C
Current random no is: 1920540202
Type is Type C
Current random no is: 1920540202
Type is Type C
Current random no is: 1920540202
Type is Type C
Current random no is: 1920540202
Type is Type C
Current random no is: 1920540202
Type is Type C
Current random no is: 1920540202
Type is Type C
Current random no is: 1920540202
Type is Type C

最佳答案

@wildplasser 是对的,你的程序中有未定义的行为。在解决该问题之前,所有有关播种或不播种的讨论都是无用的。您需要在 currentTrafficType 中为空终止符留出空间:

static char currentTrafficType[7];

当可以避免时,将返回值放在静态局部变量中通常是不好的做法。它使您的函数不可重入且线程不安全。在您的情况下,您想要返回的数据已经作为字符串文字存在,因此您可以删除整个数组:

/* return type modified from `char *` to `const char *` */
const char* newTrafficGenerator(void)
{
int i;
int count =0;

/* Use pointer rather than array */
const char *currentTrafficType;

i = random_rand();
printf("Current random no is: %d\n",i);
if (i>0 && i<32767)
{
currentTrafficType = "Type A";
}
else if(i>32767 && i<55705)
{
currentTrafficType = "Type B";
}
else
{
currentTrafficType = "Type C";
}
return currentTrafficType;
}

字符串文字保证在程序的整个运行期间都存在,因此我们可以通过指针值传递它们,而不是进行缓慢而繁琐的数组复制。请注意,字符串文字是只读的,因此只能分配给 const char * 而不是 char *

关于c - 调用该函数时显示相同的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59392565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com