我需要在 C 中实现我自己的 printf 函数。但是,我在我的函数中使用省略号(“...”)功能时遇到问题(我们需要使用省略号)。
根据我的教科书,传递给带有省略号的函数的参数应该位于存储第一个参数的正上方堆栈上。但我找不到在堆栈上任何地方传递的任何附加参数!这是我用来测试我的函数和输出的一些代码:
#include<stdio.h>
#include<stdlib.h>
int myprintf(char *str, ...)
{
//test code to view data around str on the stack:
int i;
for (i = -8; i <= 8; i++)
{
char *ptr = str + (i * 4); // ptr will iterate through the 8 bytes above and
// below str[0] on the stack
printf ("Bytes from str: %+03d \t
Ptr Addr: %x \t
Val int: %d \t
Val char: %c \n",
(i*4), ptr, *ptr, *ptr);
}
//my implementation of printf...
}
int main(void)
{
myprintf("test string", 1111, 2222, 3333);
}
这是 myprintf 函数的输出(堆栈的打印输出):
Bytes from str: -32 Ptr Addr: 8048922 Val int: 48 Val char: 0
Bytes from str: -28 Ptr Addr: 8048926 Val int: 97 Val char: a
Bytes from str: -24 Ptr Addr: 804892a Val int: 104 Val char: h
Bytes from str: -20 Ptr Addr: 804892e Val int: 32 Val char:
Bytes from str: -16 Ptr Addr: 8048932 Val int: 0 Val char:
Bytes from str: -12 Ptr Addr: 8048936 Val int: 118 Val char: v
Bytes from str: -08 Ptr Addr: 804893a Val int: 93 Val char: ]
Bytes from str: -04 Ptr Addr: 804893e Val int: 37 Val char: % <- my other variables should be here and above
Bytes from str: +00 Ptr Addr: 8048942 Val int: 116 Val char: t <-"test string"
Bytes from str: +04 Ptr Addr: 8048946 Val int: 32 Val char: <-" string"
Bytes from str: +08 Ptr Addr: 804894a Val int: 105 Val char: i <-"ing"
Bytes from str: +12 Ptr Addr: 804894e Val int: 0 Val char:
Bytes from str: +16 Ptr Addr: 8048952 Val int: 3 Val char:
Bytes from str: +20 Ptr Addr: 8048956 Val int: 0 Val char:
Bytes from str: +24 Ptr Addr: 804895a Val int: 0 Val char:
Bytes from str: +28 Ptr Addr: 804895e Val int: -1 Val char: �
Bytes from str: +32 Ptr Addr: 8048962 Val int: 0 Val char:
据我了解,值 1111、2222 和 3333 应该位于此堆栈打印输出中的某个位置。当我调用函数时这些值去哪里了?
编辑:我无法在我的实现中使用“stdarg.h”库。