Reputation: 669
I have used rand function to generate a random number. I want to collect this number to a char buffer[10]
or to a char *ptr
main()
{
char *ptr;
int a;
srand(time(NULL));
a = rand();
}
I want to copy the value in a to a buffer or point it by char *ptr
, please help me out in this
Upvotes: 0
Views: 262
Reputation: 279215
Just for reference, here's how to use snprintf
when you don't know in advance how big the buffer needs to be:
size_t len = snprintf(NULL, 0, "%d", a) + 1;
char *ptr = malloc(len);
if (!ptr) {
// memory allocation failed, you must decide how to handle the error
} else {
snprintf(ptr, len, "%d", a);
... // some time later
free(ptr);
}
However, since your code is written in an old style (no return type for main
and all variables declared at the start of the function), it may be that your C implementation doesn't have snprintf
. Beware that Microsoft's _snprintf
is not a direct substitute: when it truncates the output it doesn't tell you how much data there is to write.
In this case you can use the value RAND_MAX
to work out how many digits the value might have, and hence how big your buffer needs to be. 10 is not sufficient on Linux, where RAND_MAX
is 2147483647
, and so you need 11 bytes for your nul-terminated string.
Btw, I've neglected the possibility of snprintf
indicating an error other than truncation, which it does with the return value -1. That's because %d
can't fail.
Upvotes: 3
Reputation: 43518
char ptr[10];
sprintf(ptr,"%d",a);
If you want to use char *ptr
char *ptr = malloc(10*sizeof(char));
sprintf(ptr,"%d",a);
// And If you want to free allocated space for ptr some where:
free(ptr);
Upvotes: 0
Reputation: 789
If your compiler is GCC:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
main()
{
char *ptr;
int a;
srand(time(NULL));
a = rand();
asprintf(&ptr, "%d", a);
printf("%s\n", ptr);
//DO SOMETHING
free(ptr);
}
Upvotes: 0
Reputation:
It's safer to use snprintf()
.
int answer = 42;
char buf[32];
snprintf(buf, sizeof(buf), "%d", answer);
printf("The answer is: %s\n", buf);
If you want to use a dynamically allocated buffer:
const size_t size = 32;
char *buf = malloc(size);
if (buf != NULL) {
snprintf(buf, size, "%d", answer);
}
Upvotes: 0