Problems passing argv to function using cstdarg

Program fails to list input arguments one at a time. Gives programing error (Access violation reading location 0x000002430A502000). On the console it list the 1st argument in the input, then list all the other on the same line plus MANY THOUSANDS of other chars many not ascii chars (anything form 0 to 255).

// How to pass argv to a Function that takes variable Number of arguments
// Input parameters are "a1", "2bb", "3ccc", "dddd4", "eeeee5"


// Files to Include
#include "Shlwapi.h"
#include <cstdarg>
#include <iostream>

void listProgramInputParameters(int count, ...)
{
va_list ap;
va_start(ap, count);

for (int i = 1; i < count; i++)
std::cout << "The value of the input parameter " << i << " = " << va_arg(ap, std::string) << std::endl;

va_end(ap);
}

int main(int argc, char* argv[])
{
listProgramInputParameters(argc, argv);
}
C-style variadic functions aren't the right tool here. A loop is enough:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
void print_arguments(int argc, char** argv)
{
  for (int i = 0; i < argc; ++i)  std::cout << argv[i] << '\n';
}

int main(int argc, char** argv)
{
   print_arguments(argc, argv); 
}
argv isn't a variadic argument. It's just a pointer-to-pointer-to-char. So you can't pass it as a c-style variadic param.
The argv parameter is represented in main as either a pointer-to-pointer-to-char or pointer-to-[]-to-char. A regular array of C strings, a 2D array of chars.

1
2
int main(int argc, char** argv)
int main(int argc, char* argv[])

A regular array when passed into a function decays to a pointer, and argv is certainly being passed into the main function.

Why not argv[][]? Not allowed. Can't declare a static 2D array without one of the dimensions to be a known value.

Some implementations allow for additional parameters after argc and argv, though that is non-standard.

Which version of main's parameter list is used is personal preference, they mean the same thing. I've used them both at one time or another. The type of code I write I don't often use command-line arguments so I use the abbreviated form of int main().
Thanks VERY much. I was trying to do it the hard way.
Topic archived. No new replies allowed.