Passing Char Array into a function in C

I can not access the array from main in the function. 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. 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]);

       }
 }

Upvotes: 0

Views: 15041

Answers (2)

Harry
Harry

Reputation: 11688

You've declared an array of 7 pointers to char. You initialized it with 3 of them. 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.

Upvotes: 2

sjsam
sjsam

Reputation: 21965

With

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

You have an array of pointers to 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++)
.
.

Upvotes: 0

Related Questions