传递多个单独的字符串来运行

时间:2014-02-11 02:58:13

标签: c

我有几个字符串,我试图传递给一个函数进行处理。功能参数必须保持不变。我认为循环字符串,调用函数将是要走的路,但我不知道如何将几个不同的命名字符串传递给函数。这就是我从

开始的
#include <stdio.h>
void convert(char s[], int counts[]);

int main(void)
{
     int aray[2];
     char text0[] = "This is one of Several strings2use.";
     char text1[] = "This sample has less than 987654321 leTTers.";
     char text2[] = "Is thIs a string?  (definitely)";
     """ how do i pass each string one by one into the function? im not trying to
         call the function 3 separate times for each string"""
}

void convert(char s[], int counts[])
{
    """this function grabs each string and processes it to find word counts and
    character counts. does not return anything and accepts one string at a time"""
}

3 个答案:

答案 0 :(得分:2)

使用变量参数查找示例代码。

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

void sample (int num, char *p, ... )
{
 va_list arguments;                     
 char * temp;
 int x = 0;

 /* Initializing arguments to store all values after num */
 va_start ( arguments, num );  
 printf ("Num of addr[%d]\n", num);
 printf ("[%p] ", p);
 for ( ; x < num-1; x++ )        
 {
     temp = va_arg ( arguments, char* ); 
 printf ("[%p] ", temp);
 }
 va_end ( arguments );                
 printf ("\n");        
}

int main()
{
  char *test[5]= {"aaa", "bbb", "ccc", "ddd", "eee"};
  printf( "[%p] [%p] [%p] [%p] [%p]\n",test[0],test[1],test[2],test[3],test[4]);
  sample (sizeof(test)/sizeof(test[0]), test[0],test[1],test[2],test[3],test[4] );
}

答案 1 :(得分:0)

要将多个参数传递给函数,可以引用printf函数语法。但是,更容易满足您的要求是使用指针数组。有关详细信息,请参阅以下示例。

void sample (int num, unsigned char **p)
{
printf (" \n %d %s %s %s %s %s \n",num, p[0],p[1],p[2],p[3],p[4]);
}

main(void)   
{

  unsigned char *Test [5] = {"aaa", "bbb", "ccc", "ddd", "eee"};
  sample (sizeof (Test)/sizeof(Test [0]),  Test);
}

答案 2 :(得分:0)

这里,如上所述,您可以使用带有变量参数的函数以及anxm 2-D数组,其中n和m分别是行和列,然后您可以简单地将该数组传递给函数..但是如果您你应该使用函数中可变数量的参数来使用不同的数组。在将它们实现到函数中之前,请先了解一下c变量参数的基本概念。以下链接对创建函数很有用。

http://www.tutorialspoint.com/cprogramming/c_variable_arguments.htm