我已经使用 rand 函数来生成一个随机数。我想把这个号码收集到一个char buffer[10]或一个char *ptr
main()
{
char *ptr;
int a;
srand(time(NULL));
a = rand();
}
我想将 a 中的值复制到缓冲区或指向它char *ptr,请帮助我
我已经使用 rand 函数来生成一个随机数。我想把这个号码收集到一个char buffer[10]或一个char *ptr
main()
{
char *ptr;
int a;
srand(time(NULL));
a = rand();
}
我想将 a 中的值复制到缓冲区或指向它char *ptr,请帮助我
仅供参考,snprintf当您事先不知道缓冲区需要多大时,这里是如何使用的:
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);
}
但是,由于您的代码是用旧样式编写的(没有返回类型,main并且所有变量都在函数开头声明),因此您的 C 实现可能没有snprintf. 请注意,Microsoft_snprintf不是直接替代品:当它截断输出时,它不会告诉您要写入多少数据。
在这种情况下,您可以使用该值RAND_MAX来计算该值可能有多少位,因此您的缓冲区需要多大。10 在 Linux 上是不够的,其中RAND_MAXis 2147483647,因此您的 nul 终止字符串需要 11 个字节。
顺便说一句,我忽略了snprintf指示截断以外的错误的可能性,它使用返回值-1。那是因为%d不能失败。
您可以使用
char x[10];
sprintf(x, "%d", integer_number);
char ptr[10];
sprintf(ptr,"%d",a);
如果你想使用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);
使用起来更安全snprintf()。
int answer = 42;
char buf[32];
snprintf(buf, sizeof(buf), "%d", answer);
printf("The answer is: %s\n", buf);
如果要使用动态分配的缓冲区:
const size_t size = 32;
char *buf = malloc(size);
if (buf != NULL) {
snprintf(buf, size, "%d", answer);
}
如果您的编译器是 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);
}