整数到字符串方法

时间:2018-10-24 06:00:33

标签: c mplab

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

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

2 个答案:

答案 0 :(得分:1)

正如注释和其他答案中已经提到的那样,返回局部变量(也称为buffer)是您永远都不会做的事情,因为一旦函数返回,局部变量将被销毁。

此外,缓冲区太小而无法容纳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

答案 1 :(得分:0)

您正在尝试返回已在堆栈上分配了空间的buffer

函数返回后堆栈立即被破坏。所以现在返回的值只是一个悬空指针。

此外,缺少空终止符。