串口调试printf()函数

    xiaoxiao2022-07-07  138

    #include<stdio.h> //int printf(const char *format,...) //format:固定参数 //...:可变参数 //可以使用gcc中的__attribute__选项来设置指定的对齐大小。 //1.__attribute__((packed))取消编译器在编译过程中字节对齐的优化,以实际占用字节对齐。 //2.__attribute__((aligned(n))),所有结构体成员按照n对齐,如果成员变量大与n,则按照最大的成员变量的字节数对齐 struct person { char *name; int age; char score; int id; } struct person1 { char *name; int age; char score; int id; }__attribute__((packed)); struct person2 { char *name; int age; char score; int id; }__attribute__((aligned(n))); //int printf(const char *format,...) //原理 X86平台,GCC默认4字节对齐,函数调用时参数传递是使用堆栈来实现的 //目的 将所有传入的参数全部打印出来 //堆栈也是连续空间 //指针对连续空间操作时,1,取值。2,移动指针。 int push_test(const char * format,...) { char *p = (char *)&format; int i ; struct person per1; printf("arg1 : %s\n",format); p += sizeof(char *);//因为之前的format是char *类型 i = *((int *)p); printf("arg2 : %d\n",i); per1 = *((struct person *)p); printf("arg3: .name = %s, .age = %d, .socre = %c, .id = %d\n",\ per1.name,per1.age,per1.score,per1.id); p += sizeof(int);//因为之前的12356是int类型? return 0; } int main(int argc,char **argv) { struct person per = {"Posiden",7,'C',777}; char *p = (char *)&format; int i; printf("sizeof(char ) = %d\n", sizeof(char )); printf("sizeof(int ) = %d\n", sizeof(int )); printf("sizeof(char *) = %d\n", sizeof(char *)); printf("sizeof(char **) = %d\n", sizeof(char **)); push_test("ccccc"); push_test("ccccc",123456); push_test("ccccc",123456,per); return 0; }

     

    最新回复(0)