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;
}
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);
}