将指针传递给函数

1 c pointers

我对我的计划有疑问

#include<stdio.h>

int myFunc(char **);
main()
{
    char *a[2]={"Do","While"};
    myFunc(a);
}

int myFunc(char **P)
{
    /* Here I want to print the strings passed but I'm unable to
       print the strings I just tried the below statement which
       printed just the first letter which is 'D'*/
       printf("%c",**P);
}
Run Code Online (Sandbox Code Playgroud)

当我试着

printf("%s",**P);
Run Code Online (Sandbox Code Playgroud)

我得到运行时错误.所以有人可以帮帮我吗?

谢谢Madhu

Căt*_*tiș 11

将size作为参数,以允许函数知道数组中有多少个字符串.然后,您应该迭代数组并打印每个数组.

int myFunc( char** p, int size)
{
  for( int i = 0; i < size; ++i)
  {
     printf("%s", p[i]);
  }
}
Run Code Online (Sandbox Code Playgroud)

稍后编辑(根据要求:-))

int main( int, char**)
{
   char *a[2]={"Do","While"};
   myFunc( a, 2); // Could be myFunc( a, sizeof(a)/sizeof(char*));
   // ...
   return 0; 
}
Run Code Online (Sandbox Code Playgroud)


qrd*_*rdl 8

太多的明星 - 试试

printf("%s",*P);
Run Code Online (Sandbox Code Playgroud)

而且你需要%s格式说明符 - %c仅适用于单个字符.

如果要打印所有字符串,则需要在数组中传递字符串数,然后从循环中打印这些字符串.

检查CătălinPitiş建议的代码.要传递字符串数,可以像这样调用函数:

myFunc(a, sizeof(a)/sizeof(a[0]));
Run Code Online (Sandbox Code Playgroud)

  • @ n-alexander如果你在评论和投票前阅读帖子会很好,从"如果你想要打印所有字符串......"开始 (3认同)

sha*_*oth 5

for( int i = 0; i < 2; i++ ) {
    char* string = P[i];
    printf( "%s", string );
}
Run Code Online (Sandbox Code Playgroud)

你应该使用一些方法将数组大小传递给函数 - 或者将它作为int参数传递,

int myFunc(char **P, int size)
{
    for( int i = 0; i < size; i++ ) {
        //whatever here
    }
}
Run Code Online (Sandbox Code Playgroud)

或者总是将一个零值附加到数组中,并且只有在找到零值时才循环.

char* array[] = { "String1", "String2", 0 };    
Run Code Online (Sandbox Code Playgroud)

否则你将难以维护代码.