C
C
COUT_man2021-01-01 12:48:07
C++ / C#
COUT_man, 2021-01-01 12:48:07

How to properly use the stdarg.h library in C and does it work with WSL?

I continue my thorny path of learning C. I ran into the question of the need to write a function with the possibility of accepting a non-regular number of variables.
By assignment, it must use the stdarg.h library. But I can't understand how it works. I've read several articles that describe the principle in a very clear way... And in practical application, I go into a blunt. Whether the described principle is not true, tol and I do not understand something. When I try to get a value, instead of the expected one, I get a nonsense of characters, letters and numbers. I'm trying to use everything on WSL Ubuntu.
What am I doing wrong?
To try to understand the principle, I implemented a mock code:

spoiler
#include <stdio.h>
#include <stdarg.h>

int main(char fmt, ...)
{
    va_list ap;
    char c;
    char *s;

    c = fmt;
    va_start(ap, fmt);
    while (1)
    {
    if (c == 'c')
    	{
      printf("make c\n");
      c = (char)va_arg(ap, int);
    		printf("%c\n", c);
      break ;
    }
    if (c == 's')
    	{
      printf("make s\n");
      s = va_arg(ap, char *);
    		printf("%s\n", s);
      break ;
    }
    printf("not eat!\n");
    break ;
  }
    va_end(ap);
    return (0);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Demin, 2021-01-01
@COUT_man

With main it doesn't work that way. The main signature with command line arguments looks like this:

int main(int argc, char **argv) {
}

Whatever is the equivalent of your code. Main is passed a pointer to an array of strings, but your code assumes that all arguments will be passed on the stack. Because of this, nothing works.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question