Frage

I would like to create a buffer and then write random data in it.

here's what I got so far

uint8_t size = 10;
int* buffer = malloc (size*sizeof(uint8_t));
int i;
for (i=0; i<size; i++)
{
buffer[i]=(rand()%100)+1;
}
printf("Content of buffer = %d\n", buffer);

the result is wandom yes but only 8 numbers instead of 10.

I would like to get a buffer with the content of size and random numbers in it.

thanks in advance

War es hilfreich?

Lösung

You need

malloc (size*sizeof(int))

instead of

malloc (size*sizeof(uint8_t))

or maybe you need

uint8_t* buffer = malloc (size*sizeof(uint8_t));

It depends if you want a buffer of 10 int of a buffer of 10 uint8_t.

For printing the content of the buffer use:

for (i = 0; i < size; i++)
{
  printf("%d\n", buffer[i]) ;
}

Following line only prints the address of the buffer.

printf("Content of buffer = %d\n", buffer);

Andere Tipps

If you want a buffer of arbitrary size allocated with random data, you may want to seed your random number generator with the current time and then call random() repeatedly:

#include <time.h>
#include <stdlib.h>

char *allocate_random_heap_buffer(size_t size) {
    time_t current_time = time(NULL);
    srandom((unsigned int) current_time);
    char* allocatedMemory = (char *) malloc(size);

    for (int bufferIndex = 0; bufferIndex < size; bufferIndex++) {
        uint8_t randomNumber = (uint8_t) random();
        allocatedMemory[bufferIndex] = randomNumber;
    }

    return allocatedMemory;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top