创建一个带有变量 acguments(字符串)的函数,输出字符串 ant 计算它们
Create a function with variable acguments (strings) which outputs that strings ant count them
我是 C 语言的新手。我仍然没有真正得到指点。有人可以帮助我吗?
我必须创建一个带有可变参数(字符串)的函数,它输出的字符串蚂蚁会计算它们。
#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;
}
您不能直接遍历一组变量参数,因为将它们传递给函数的方式在很大程度上取决于具体实现。
而是使用 va_list
遍历它们。
#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);
}
我是 C 语言的新手。我仍然没有真正得到指点。有人可以帮助我吗? 我必须创建一个带有可变参数(字符串)的函数,它输出的字符串蚂蚁会计算它们。
#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;
}
您不能直接遍历一组变量参数,因为将它们传递给函数的方式在很大程度上取决于具体实现。
而是使用 va_list
遍历它们。
#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);
}