gpt4 book ai didi

c - 整数转字符串方法

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

我正在尝试创建一个整数(字符串最多四位数字)。这是我的方法:

char  *ToInt( int Value)
{
char buffer[4];
sprintf(buffer, "%04d", Value);
return buffer;
}

之后字符串被分成每个字节并将其发送到 7 段 LCD。问题是我收到了警告

 warning: (365) pointer to non-static object returned

以及所有这些错误

 C:\Program Files (x86)\Microchip\xc8\v1.45\sources\common\doprnt.c:538: warning: (373) implicit signed to unsigned conversion
C:\Program Files (x86)\Microchip\xc8\v1.45\sources\common\doprnt.c:541: warning: (373) implicit signed to unsigned conversion
C:\Program Files (x86)\Microchip\xc8\v1.45\sources\common\doprnt.c:1259: warning: (373) implicit signed to unsigned conversion
C:\Program Files (x86)\Microchip\xc8\v1.45\sources\common\doprnt.c:1305: warning: (373) implicit signed to unsigned conversion
C:\Program Files (x86)\Microchip\xc8\v1.45\sources\common\doprnt.c:1306: warning: (373) implicit signed to unsigned conversion
C:\Program Files (x86)\Microchip\xc8\v1.45\sources\common\doprnt.c:1489: warning: (373) implicit signed to unsigned conversion
C:\Program Files (x86)\Microchip\xc8\v1.45\sources\common\doprnt.c:1524: warning: (373) implicit signed to unsigned conversion

最佳答案

正如评论和其他答案中已经提到的,返回局部变量(又名缓冲区)是你永远不应该做的事情,因为一旦函数返回,局部变量就会被销毁。

此外,缓冲区太小,无法容纳 4 个字符,因为 C 中的字符串需要额外的字符来零终止字符串。因此,要保存 4 个字符,您(至少)需要 buffer[5]。但是,请注意 %04d 并不能确保打印正好 4 个字符。高 int 值将产生更多字符并导致(更多)缓冲区溢出。因此,您需要一个可以保存最大(可能是负)整数的打印的缓冲区。

那么你能做什么呢?

你有两个选择。 1) 在函数内部使用动态内存分配或 2) 让调用者向函数提供目标缓冲区。

它可能看起来像:

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

// The maximum number of chars required depends on your system - see limits.h
// Here we just use 64 which should be sufficient on all systems
#define MAX_CHARS_IN_INT 64

char* intToMallocedString(int Value)
{
char* buffer = malloc(MAX_CHARS_IN_INT); // dynamic memory allocation
sprintf(buffer, "%04d", Value);
return buffer;
}

// This could also be a void function but returning the buffer
// is often nice so it can be used directly in e.g. printf
char* intToProvidedString(char* buffer, int Value)
{
sprintf(buffer, "%04d", Value);
return buffer;
}

int main(void) {
int x = 12345678;
char str[MAX_CHARS_IN_INT]; // memory for caller provided buffer

char* pStr = intToMallocedString(x);
intToProvidedString(str, x);
printf("%s - %s\n", str, pStr);

free(pStr); // dynamic memory must be free'd when done
return 0;
}

输出:

12345678 - 12345678

关于c - 整数转字符串方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52961939/

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