I am creating some wrapper functions using vsprintf() function but its failing if column value > 0 .I compiled this code with different complier but getting the same result. You can check result of this code here -> Compiler Explorer
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#define MAX_ROW 4
#define MAX_COL 16
typedef struct {
union {
char data[MAX_ROW][MAX_COL];
char bytes[MAX_ROW * MAX_COL];
};
char size;
}M_BUFFER_Typedef;
char M_BufferPrintf(M_BUFFER_Typedef *buffer,const char *fmt,char row,char col,...) {
if(row > MAX_ROW)
return 0;
va_list arg;
va_start(arg,col);
vsprintf((char *)&buffer->data[row][col],fmt,arg);
va_end(arg);
return 1;
}
int main() {
M_BUFFER_Typedef buffer = {
0
};
M_BufferPrintf(&buffer,"H : %d %.02f",0,0,5,1.2695);
M_BufferPrintf(&buffer,"H : %d %.02f",1,2,6,30.2695);
M_BufferPrintf(&buffer,"H %.02f",2,0,100.2695);
M_BufferPrintf(&buffer,"H : %d ",3,0,9);
printf("\n%s",buffer.data[0]);
printf("\n%s",buffer.data[1]);
printf("\n%s",buffer.data[2]);
printf("\n%s",buffer.data[3]);
}
Code output:
> ASM generation compiler returned: 0
> Execution build compiler returned: 0\n
> Program returned: 0
H : 5 1.27
//if col value 2 -> nothing copied here
H 100.27
H : 9
CodePudding user response:
It works fine, nothing is failing - you simply do not understand how it works
The second one does not work as you expect because you print from the first character of row 1
, but vsprintf
has written starting from the char number three and the two first characters are still zero.
if you change the line printing it to:
printf("\n%s",&buffer.data[1][2]);
It will print what you expect there.
You can print the content of the row to see what is there:
printf("Content of the row 2: "); for(int i =0; i < MAX_COL; i ) printf("%d ", buffer.data[1][i]);
printf("\n");
https://godbolt.org/z/nav4EK6WT
As you see the row starts from the null character, thus printf the string outputs nothing.