vsprintf 函数不适用于结构二维数组

vsprintf function not working with structure 2d array

我正在使用 vsprintf() 函数创建一些包装函数,但如果列值 > 0 则它会失败。我使用不同的编译器编译了这段代码,但得到了相同的结果。您可以在此处查看此代码的结果 -> 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]);
}

代码输出:

> 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 

它工作正常,没有任何问题 - 你只是不明白它是如何工作的

第二个不能像你预期的那样工作,因为你从行 1 的第一个字符开始打印,但是 vsprintf 已经从第三个字符开始写了,前两个字符仍然是零。

如果您将打印它的行更改为:

  printf("\n%s",&buffer.data[1][2]);

它将打印出您期望的内容。

您可以打印该行的内容以查看其中的内容:

  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

如您所见,该行从空字符开始,因此 printf 字符串不输出任何内容。