I'm new at C. And I still don't really get pointers. Could someone help me, please. I have to create a function with variable arguments (strings) which outputs that strings ant count them.
#include <stdio.h>
void PrintAndCount(const char* s, ...)
{
char **p = &s;
while(*p != NULL)
{
printf("%s\n", *p);
(*p) ;
}
}
int main()
{
char s1[] = "It was a bright cold day in April.";
char s2[] = "The hallway smelt of boiled cabbage and old rag mats. ";
char s3[] = "It was no use trying the lift.";
PrintAndCount(s1, s2, s3, NULL);
return 0;
}
CodePudding user response:
You can't directly iterate though a set of variable arguments, since how they're passed to a function is highly implementation specific.
Instead, use a va_list
to iterate through them.
#include <stdarg.h>
void PrintAndCount(const char* s, ...)
{
va_list args;
va_start(args, s);
printf("%s\n", s);
char *p = va_arg(args, char *);
while(p != NULL)
{
printf("%s\n", p);
p = va_arg(args, char *);
}
va_end(args);
}
CodePudding user response:
You can pass a vector of strings.
void Print_Strings(const std::vector<string>& data)
{
const unsigned int quantity = data.size();
for (unsigned int i = 0u; i < quantity; i)
{
std::cout << i << " " << data[i] << "\n";
}
}
A vector eliminates the need for variable arguments.