简体   繁体   中英

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. The console also shows me, that the code always generates the same "204" value everytime even though I'm using the rand() function.

#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. Use srand(time(NULL)) to seed. Also remove i++; statement from your for loop body.

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. 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.

This is what your sendbuf array contains with your current code :

[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 ...

In order to fix this, remove i++ from the for loop body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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