C18 sprintf()给出语法错误[重复]

问题描述 投票:0回答:2

我似乎在线上有语法错误

FSFILE *file; 

在添加sprintf()行后的以下代码中。代码工作直到我添加了char文本,textresult和sprintf()。我似乎无法找出它的错误。我正在使用C18编译器。代码用于使用SPI将数据写入SD卡。 char txt []是带温度传感器的测量值,例如:23,5。但我想为此添加更多文字。目标是每隔5分钟在SD卡上存储一个测量值,以及时间戳等。我正在使用PIC18f27j53。

void writeFile()
{
    unsigned char txt[]={ftc(result,0),ftc(result,1),0x2C,ftc(result,3)};
    unsigned char text[]= "hello";  
    unsigned char textresult[];   
    sprintf(textresult, "%c%c", txt, text); 
    //unsigned char size = sizeof(result)-1;
    FSFILE *file;
    file = FSfopenpgm("DATA.TXT", "w");
    if(file == NULL)while(1);
    if(FSfwrite((void *) txt, 1, 4, file)!=4)while(1);
    if(FSfclose(file)!=0)while(1);
}
c printf c89 c18
2个回答
0
投票

在声明变量的位置后移动sprintf(...)


0
投票

我不知道ftc做了什么,但你的txt可能不是'\0'终止,如果你想用它作为一个字符串,它必须是'\0'终止。

另外你的textresult是一个空数组,如果你试图在没有可用空间的地方写东西,你会发生什么?

unsigned char textresult[20];

会是对的。

另请注意,%c中的printf期望单个char值,您正在传递指向整个chars序列的指针,这是未定义的行为。你必须要么使用%s(并且为此txt必须是'\0'终止)或者你传递txt[0],单个char

sprintf(textresult, "%c%c", txt[0], text); 

// or

unsigned char txt[]={ftc(result,0),ftc(result,1),0x2C,ftc(result,3), 0};
...
sprintf(textresult, "%s%c", txt, text); 

如果编译器希望在函数的开头声明所有变量,请移动

FSFILE *file;

sprintf电话之前。

© www.soinside.com 2019 - 2024. All rights reserved.