gpt4 book ai didi

c - 将 int 存储在 char* 中 [C]

转载 作者:太空宇宙 更新时间:2023-11-04 06:03:59 27 4
gpt4 key购买 nike

int main()
{
int n = 56;
char buf[10]; //want char* buf instead
sprintf(buf, "%i", n);
printf("%s\n", buf);

return 0;
}

这段代码有效,我的问题是如果我想要相同的行为,buf 是一个 char* 怎么办?

最佳答案

写作时的主要区别

char* buf;

是不是未初始化,没有分配内存,所以你得自己注意了:

char* buf = malloc(10 * sizeof(char));
// ... more code here
free(buf); // don't forget this or you'll get a memory leak

这叫做 dynamic memory allocation (与静态分配相反)并且它允许你像 changing the amount of allocated memory at runtime 这样的好东西使用 realloc 或在 malloc 调用中使用变量。另请注意,如果内存量太大,内存分配可能会失败,在这种情况下,返回的指针将为 NULL

从技术上讲,上面的 sizeof(char) 是不需要的,因为 1 个 char 的大小总是 1 个字节,但大多数其他数据类型更大,乘法是重要 - malloc(100) 分配 100 个字节,malloc(100 * sizeof(int)) 分配 100 个 int 所需的内存量在 32 位系统上通常为 400 字节,但可能会有所不同。

int amount = calculate_my_memory_needs_function();
int* buf = malloc(amount * sizeof(int));
if (buf == NULL) {
// oops!
}
// ...
if (more_memory_needed_suddenly) {
amount *= 2; // we just double it
buf = realloc(buf, amount * sizeof(int));
if (!buf) { // Another way to check for NULL
// oops again!
}
}
// ...
free(buf);

另一个有用的函数是 calloc,它有两个参数(第一个:要分配的元素数,第二个:元素的字节大小)并将内存初始化为 0。

关于c - 将 int 存储在 char* 中 [C],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13895073/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com