Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array of strings to functions C

i am currently confused as to how i can pass an array of strings to a function. I have created a one-dimensional array. The method that i have done works but it seems redundant and i think there is a better way of doing this yet i am unsure how. I am trying to find a way where i can pass all 4 elements to the function at one time.

Here is the sample of my code.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void sort(char *,char *,char *, char *);//Function prototype
int main()
{
    char *string_database[4]={'\0'};
    string_database[0]="Florida";
    string_database[1]="Oregon";
    string_database[2]="California";
    string_database[3]="Georgia";
    sort(string_database[0],string_database[1],string_database[2],string_database[3]);
    return 0;
}

void sort(char *string1, char *string2, char *string3, char *string4)
{

    printf("The string is= %s\n",string1);
    printf("The string is= %s\n",string2);
    printf("The string is= %s\n",string3);
    printf("The string is= %s\n\n\n",string4);

}

Thank you in advance, i appreciate any replies to my problem.

like image 359
Max twelve Avatar asked Jun 23 '15 10:06

Max twelve


People also ask

How can we pass array to function in C?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

Can you pass a string to a function in C?

Passing Strings to Function As strings are character arrays, so we can pass strings to function in the same way we pass an array to a function.

How do you pass an array of values to a function?

Answer: An array can be passed to a function by value by declaring in the called function the array name with square brackets ( [ and ] ) attached to the end. When calling the function, simply pass the address of the array (that is, the array's name) to the called function.


1 Answers

You can do it like this:

void sort(char **, int);
int main()
{
    char *string_database[5]={'\0'};
    string_database[0]="Florida";
    string_database[1]="Oregon";
    string_database[2]="California";
    string_database[3]="Georgia";

    sort(string_database, 4);
    return 0;
}

void sort(char **str, int n)
{
    int i = 0;
    for (i = 0; i < n; i++)
      printf("The string is= %s\n",str[i]);

}
like image 68
Arjun Mathew Dan Avatar answered Oct 22 '22 15:10

Arjun Mathew Dan