简体   繁体   English

在C中使用rand()

[英]Using rand() in C

I am sending a large 1d array of generated random values with the data type uint8_t using the rand() function in a TCP server, but the data type might be an issue since I don't receive anything on the TCP client side. 我正在使用TCP服务器中的rand()函数发送数据类型为uint8_t的生成的随机值的大型一维数组,但是由于我在TCP客户端上什么都没收到,因此数据类型可能是个问题。 The console also shows me, that the code always generates the same "204" value everytime even though I'm using the rand() function. 控制台还向我显示,即使我使用的是rand()函数,代码也始终会生成相同的“ 204”值。

#define DEFAULT_BUFLEN 19200

int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
int c, iResult;
char sendbuf [DEFAULT_BUFLEN];
int sendbuflen = DEFAULT_BUFLEN;
uint8_t* p;
int i;


// Send uint8_t data to client
p = (uint8_t*)sendbuf;

for (i = 0; i < 19200; i++)
{
  p[i] = rand() % 256; //range 0-255 */
  i++;
  printf("%d\n", p[i]);
}
return 0;

iResult = send(client_socket, sendbuf, sendbuflen, 0);
}

You need to seed your rand function. 您需要rand函数。 Use srand(time(NULL)) to seed. 使用srand(time(NULL))进行播种。 Also remove i++; 同时删除i++; statement from your for loop body. 您的for循环正文中的声明。

The error here is that you are incrementing your iteration variable, i, before printing the random value you generated and stored in the preceding place in the array. 这里的错误是,在打印生成的并存储在数组前一位置的随机值之前,您正在递增迭代变量i。 The reason you see 204 every time printf is called is because printf is printing an uninitialized integer that on your compiler just happens to be 204. If you were to memset the sendbuf array to zero before the for loop, you would see printf print zero every time. 每次调用printf都会看到204的原因是因为printf正在打印一个未初始化的整数,而该整数在编译器上恰好是204。如果要在for循环之前将sendbuf数组设置为零,则您会看到printf每次打印都会输出零。时间。

This is what your sendbuf array contains with your current code : 这是sendbuf数组包含在当前代码中的内容:

[0] = random value [1] = uninitialized value <- printf prints this on the first iteration of the for loop [2] = random value [3] = uninitialized value <- printf prints this on the second iteration of the for loop ... [0] =随机值[1] =未初始化值<-printf在for循环的第一次迭代中打印此结果[2] =随机值[3] =未初始化值<-printf在for循环的第二次迭代中打印此结果...

In order to fix this, remove i++ from the for loop body. 为了解决此问题,请从for循环体内删除i ++。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM