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.
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.
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.
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.
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With