简体   繁体   English

将Char数组传递给C函数

[英]Passing Char Array into a function in C

I can not access the array from main in the function. 我无法从函数中的main访问数组。 How do i correct this ? 我该如何纠正? Whenever I compile it say the argument 1 is of type **char and the argument 1 passed to fre in incompatible. 每当我编译它时,都说参数1是** char类型,而参数1传递给fre却不兼容。 Do i need to change any syntaxes ? 我需要更改任何语法吗?

void fre(char *asd);

int main()

 {
   char *names[7]={"Jayan Tennakoon","John Long","Robert Lang"};

   int i;

   for(i=0;i<7;i++)
     {

        printf("%s\n",names[i]);

     }

     fre(names);

     return 0;

 }

 void fre(char *asd)
   {
     int i;

     for(i=0;i<7;i++)
       {

          printf("%s\n",asd[i]);

       }
 }

You've declared an array of 7 pointers to char. 您已经声明了一个由7个指向char的指针组成的数组。 You initialized it with 3 of them. 您使用其中的3个对其进行了初始化。 You need to pass an array of pointers, not a pointer to an array of chars. 您需要传递一个指针数组,而不是一个指向字符数组的指针。 Based on the comments I'll add a few more ways to declare the arrays that might make it clear what the different ways actually mean. 基于这些注释,我将添加一些其他方法来声明数组,这可能使您清楚地知道不同方法的实际含义。

#include <stdio.h>
#include <stdlib.h>

void fre(char *asd[]);

int main(void) {
  char * name  [ ] = {"Jayan Tennakoon","John Long","Robert Lang"};
  char * names [7] = {"Jayan Tennakoon","John Long","Robert Lang"};
  char   names2[7] = {'H', 'e', 'l','l','o','\0'};
  char **names3   = names;

  printf("names2 = %s\n",names2);
  printf("names3[0] = %s\n",names3[0]);
  int i;
  for(i = 0; i < 3; i++) {
    printf("%s\n",names[i]);
  }
  fre(names);
  return 0;

}

void fre(char *asd[]) {
  int i;
  for(i = 0; i < 3; i++) {
    printf("%s\n",asd[i]);
  }
}

I also had to reduce the loop from 7 to 3 or you would experience Undefined Behavior, if lucky this would be a segmentation fault, if unlucky it would likely have printed garbage but exited with a return statue of 0. 我还必须将循环从7减少到3否则您将遇到“未定义行为”,如果幸运的话,这将是一个分段错误;如果不幸的话,它可能会打印出垃圾,但返回的返回值为0。

With

char *names[7]={"Jayan Tennakoon","John Long","Robert Lang"};

You have an array of pointers to char . 您有一个指向char的指针数组。 So 所以

void fre(char *asd)

should be 应该

void fre( char *asd[], int n) 
/* it is good to pass the total(here 3) 
 * since you have initialized the first three elements
 */
{
.
.
for(i=0;i<n;i++)
.
.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM