gpt4 book ai didi

c - 如何将一个值转换为整数类型字符串?

转载 作者:行者123 更新时间:2023-11-30 17:44:17 24 4
gpt4 key购买 nike

我们都知道要转换字符串中的值,我们可以执行以下操作

char* buffer = ... allocate a buffer ...
int value = 4564;
sprintf(buffer, "%d", value);

但是如果我想将数据转换为整数缓冲区而不是字符缓冲区,我们该怎么办,基本上我想做以下事情

int* buffer = ... allocate a buffer ...
int value = 4564;
sprintf(buffer, "%d", value);

提前致谢

最佳答案

请确保将缓冲区定义为“value”的值,而不是指向“value”地址的指针。见下文:

#include <stdlib.h>
#include <stdio.h>
#include <memory.h>

int main(int argc, char** argv)
{
/* Allocate memory. */
int* buffer = malloc(sizeof(int));

int value = 1000;

/* Sets the number stored in buffer equal to value. */
*buffer = value;

/* prints 1000 */
printf("%d\n", *buffer);

/* Change value to show buffer is not pointing to the address of 'value'. */
value = 500;

/* Still prints 1000. If we had used
int* buffer = &value, it would print 500. */
printf("%d\n", *buffer);

return 0;
}

关于c - 如何将一个值转换为整数类型字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20040684/

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