简体   繁体   中英

Pass multiple strings to function c

I'm learning the basics and principles of C.

I came now to pointers, strings and structs.

Now I'm working on this code to pass arrays' content to functions.

I have this code to pass content of different arrays to function.

What I succeeded to accomplish is:

  1. How to pass one complete string because it's considered as one element of the array.
  2. How to pass array of char and ints.

The issues I have now:

  1. How to pass arrays of multiple strings to functions.
  2. How to assign a pointer to the arrays to pass them also to functions.

This is my code so far:

void print_array(char *arr,int8_t cnt);
void print_array(char *arr,int8_t cnt)
{
    int i;
    printf("Number of elements is: %d\n",cnt);
    for (i=0;i<cnt;i++)
    {

        printf("Elements of array: %s\n",arr);
    }
}

void print_len (char *arr,int8_t cnt);

void print_len (char *arr,int8_t cnt)
{
    char i,l;
    for (i=0;i<cnt;i++)
    {
        printf ("%d\n",strlen(arr));
    }
}

int main(){
char  array_1 [] = {1,2,3,4,5,6,7,8};
char  array_2 [] = {'1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G'};
char *array_3 [] = {"1st","2nd","3rd","4th","5th","6th"};
char *array_4 [] = {"Many of the designations used by manufacturers"};
char *array_5 [] = {"mm","End of Multiple Strings Array","simple bluetooth connection",
"datalogging purposes and accessing recorded data","THE OPERATING ENVIRONMENT"};
//int8_t *array_pointer[3]=(char*){&array_1,&array_2,&array_3};
int8_t cnt1 = sizeof(array_1)/sizeof(array_1[0]);
int8_t cnt2 = sizeof(array_2)/sizeof(array_2[0]);
int8_t cnt3 = sizeof(array_3)/sizeof(array_3[0]);
int8_t cnt4 = sizeof(array_4)/sizeof(array_4[0]);
int8_t cnt5 = sizeof(array_5)/sizeof(array_5[0]);
int8_t len1,len2,len3,len4,len5,i,t=0,x=0;
//print_len(*array_3,cnt3);
print_len(*array_5,cnt5);

//printf("Number of chars int the string#%d is: %d\n",i,t);

// this for testing strlen inside main
// I want to process this function outside main
/*for (i=0;i<cnt5;i++)
{
    printf ("%d\n",strlen(array_5[i]));
}*/


//print_array(array_pointer[0],cnt1);
//print_array(array_1,cnt1);
//print_array(array_2,cnt2);
//print_array(*array_3,cnt3);
//print_array(*array_4,cnt4);
print_array(*array_5,cnt5);
return 0;
}
  1. How to pass arrays of multiple strings to functions.

You need another function. Declare it as:

void print_array_2(char *arr[], int cnt);

Then, you can use:

print_array_2(array_3, cnt3);
  1. How to assign a pointer to the arrays to pass them also to functions.

You can use:

char* string_array[2] = {};
string_array[0] = array_1;
string_array[2] = array_2;
print_array_2(string_array, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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