When you are doing string_copy(my_array), you are passing a char (*)[100], i.e. pointer to char[100] array to your function. But your function is expecting a char *[], i.e. array of char pointers, because you have defined your function that way.

You can fix this by making changes so that your function (string_copy()) expects a char (*)[100], instead of a char *[].

For this, you can change your function definition as:

/* Your my_array gets converted to pointer to char[100]
   so, you need to change your function parameter
   from `char *pointer[]` to `char (*pointer)[100]` 
*/ 
/* static void string_copy(char *pointer []) */
static void string_copy(char (*pointer) [100])
{
    strcpy(pointer[0], "Hello ");
    strcpy(pointer[1], "world");
}

* Alternative Solution *

A different design/solution would be to change in your main() function so that you are actually passing a char *[], which decays into a char ** - which is fine - to string_copy(). This way you would NOT have to change your string_copy() function.

int main(int argc, const char * argv[]) {

    char my_array[10][100];
    int tot_char_arrs, i;
    char *char_arr_ptr[10];

    /* Get total number of char arrays in my_array */
    tot_char_arrs = sizeof(my_array) / sizeof(my_array[0]);

    // Store all char * 
    for (i = 0; i < tot_char_arrs; i++)
            char_arr_ptr[i] = my_array[i];

    /* Actually passing a char *[].
       it will decay into char **, which is fine
     */
    string_copy(char_arr_ptr);

    printf("%s%s\n", my_array[0], my_array[1]);
}
Answer from sps on Stack Overflow
Top answer
1 of 3
6

When you are doing string_copy(my_array), you are passing a char (*)[100], i.e. pointer to char[100] array to your function. But your function is expecting a char *[], i.e. array of char pointers, because you have defined your function that way.

You can fix this by making changes so that your function (string_copy()) expects a char (*)[100], instead of a char *[].

For this, you can change your function definition as:

/* Your my_array gets converted to pointer to char[100]
   so, you need to change your function parameter
   from `char *pointer[]` to `char (*pointer)[100]` 
*/ 
/* static void string_copy(char *pointer []) */
static void string_copy(char (*pointer) [100])
{
    strcpy(pointer[0], "Hello ");
    strcpy(pointer[1], "world");
}

* Alternative Solution *

A different design/solution would be to change in your main() function so that you are actually passing a char *[], which decays into a char ** - which is fine - to string_copy(). This way you would NOT have to change your string_copy() function.

int main(int argc, const char * argv[]) {

    char my_array[10][100];
    int tot_char_arrs, i;
    char *char_arr_ptr[10];

    /* Get total number of char arrays in my_array */
    tot_char_arrs = sizeof(my_array) / sizeof(my_array[0]);

    // Store all char * 
    for (i = 0; i < tot_char_arrs; i++)
            char_arr_ptr[i] = my_array[i];

    /* Actually passing a char *[].
       it will decay into char **, which is fine
     */
    string_copy(char_arr_ptr);

    printf("%s%s\n", my_array[0], my_array[1]);
}
2 of 3
3

you need to use a pointer to the array. here is an example with 1 dimension array:

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

static void string_copy(char **pointer) {

    strcpy(pointer[0], "Hello ");

}

int main(int argc, const char * argv[]) {

    char my_array[10];
    char * p_array = my_array;

    string_copy(&p_array);

    printf("%s\n",  my_array);

}
Top answer
1 of 3
17

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]);

}
2 of 3
5
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void sort(char *strings[], int n);//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, 4);
    return 0;
}

void sort(char *strings[], int n)
{
    int i;
    for (i=0; i<n; i++) {
        printf("String %d: %s\n", i, strings[i]);
    }
}

You usually pass the length of the array along with the array itself. The char *strings[] is really just sintactic sugar though, so if you want to keep the function prototype without parameter names you can use char **strings as well, so that the code could be like this:

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

void sort(char **, int);//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, 4);
    return 0;
}

void sort(char **strings, int n)
{
    int i;
    for (i=0; i<n; i++) {
        printf("String %d: %s\n", i, strings[i]);
    }
}

Also, as Jite below points out, using a syntax such as char *strings[] might mislead you or another reader of the code into thinking they're dealing with a static matrix, while this is not true; you should therefore opt for the more straightforward char **strings syntax.

Discussions

Passing an array of strings as parameter to a function in C - Stack Overflow
I want a simple function that receives a string and returns an array of strings after some parsing. So, this is my function signature: int parse(const char *foo, char **sep_foo, int *sep_foo_qty) ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
January 28, 2009
[C] How to pass an array of strings to a function
The three things you tried are ... to char". If you do that, then the program will try to interpret the first 8 bytes of your string as a memory address, and you'll be trying to access some memory address off who knows where. ... Thank you a lot! Works just fine. ... How do I pass an array as a function parameter, and change ... More on reddit.com
๐ŸŒ r/learnprogramming
2
1
October 5, 2022
How to pass array of strings as function parameter?
Any array variable is really just a pointer to the first value of that array. The following values are stored in the next bits of memory according to the size of the type. For instance, char should be 1 byte so an array of char is just one char-per-byte in continuous memory. In general the way to pass arrays through functions is to pass the pointer to the array followed by the size of the array since C doesn't maintain any data about the allocated memory. void handleStrings(char* strings, int rows, int columns) { int i, j; for (i = 0; i < rows; i++) { for (j = 0; j < columns; j++) { // do something with strings[i][j] } } } More on reddit.com
๐ŸŒ r/C_Programming
6
0
December 4, 2016
How to pass array of strings to a function in C - Stack Overflow
I am noob and I want to pass pointer of an array of strings to a function and that function simply prints the strings of the array using pointer arithmetic. #include #include More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
IncludeHelp
includehelp.com โ€บ c-programs โ€บ pass-an-array-of-strings-to-a-function.aspx
C program to pass an array of strings to a function
/* C program to array of strings to a function */ #include <stdio.h> // function to print strings void Strfun(char **ptr , int count) { int i=0; for(i=0;i<count;i++) { printf("\nString [%d] : %s",i,ptr[i]); fflush(stdout); } } // main function int main() { // Declare an array of pointers and assign some strings into it char *buff[4] = {"Hello function" , "How are you?"
Top answer
1 of 4
28

The warning is exactly right. Your function wants an array of pointers. You're giving it an array of arrays.

Expected:

 sep_foo:
 +------+       +-----+
 |char**|--> 0: |char*|-->"string1"
 +------+       +-----+
             1: |char*|-->"string2"
                +-----+
*sep_foo_qty-1: |...  |
                +-----+

What you provided:

           sep_foo:
           +--------------------------------+
        0: | char[MAX_STRING_LENGTH]        |
           +--------------------------------+
        1: | char[MAX_STRING_LENGTH]        |
           +--------------------------------+
MAX_QTY-1: | ...                            |
           +--------------------------------+

An array with elements of type X can "decay" into a pointer-to-X, or X*. But the value of X isn't allowed to change in that conversion. Only one decay operation is allowed. You'd need it to happen twice. In your case, X is array-of-MAX_STRING_LENGTH-chars. The function wants X to be pointer-to-char. Since those aren't the same, the compiler warns you. I'm a bit surprised it was just a warning since nothing good can come from what the compiler allowed to happen.

In your function, you could write this code:

char* y = NULL;
*sep_foo = y;

That's legal code since sep_foo is a char**, so *sep_foo is a char*, and so is y; you can assign them. But with what you tried to do, *sep_foo wouldn't really be a char*; it would be pointing to an array of char. Your code, in effect, would be attempting to do this:

char destination[MAX_STRING_LENGTH];
char* y = NULL;
destination = y;

You can't assign a pointer into an array, and so the compiler warns that the call is no good.

There are two ways to solve this:

  • Change the way you declare and allocate sep_foo on the calling side so it matches what the function expects to receive:

    char** sep_foo = calloc(MAX_QTY, sizeof(char*));
    for (int i = 0; i < MAX_QTY; ++i)
      sep_foo[i] = malloc(MAX_STRING_LENGTH);
    

    or, equivalently

    char* sep_foo[MAX_QTY];
    for (int i = 0; i < MAX_QTY; ++i)
      sep_foo[i] = malloc(MAX_STRING_LENGTH);
    
  • Change the prototype of the function to accept what you're really giving it:

    int parse(const char *foo, char sep_foo[MAX_QTY][MAX_STRING_LENGTH], int *sep_foo_qty);
    
2 of 4
15

Parameter 2 should be

char sep_foo[][MAX_STRING_LENGTH]

To clarify, you are passing a pointer to parse() and treating it as a pointer to a pointer. A multidimensional array in C is NOT an array of pointers. It is a single block of memory that is pointed to by the array variable. You cannot dereference it twice.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ [c] how to pass an array of strings to a function
r/learnprogramming on Reddit: [C] How to pass an array of strings to a function
October 5, 2022 - #include <stdio.h> #include <string.h> void options_list(char *options[], int length){ for (int i = 0; i < length; i++) { printf("%d - %s", i, options[i]); } } int main() { char stringlist[3][20]; strcpy(stringlist[0], "Start"); strcpy(stringlist[1], "Options"); strcpy(stringlist[2], "Exit"); options_list(stringlist, 3); return 0; } I tried as argument : *options[] **options options[][] All leading to errors or SIGSEGV ยท Archived post. New comments cannot be posted and votes cannot be cast. Share ... This is what you're looking for. void options_list(char (*options)[20], int length){ for (int i = 0; i < length; i++) { printf("%d - %s\n", i, options[i]); } } This says that options is a pointer to an array of 20 chars.
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 88153-how-pass-array-strings-function-argument.html
How to pass an array of strings as a function argument?
April 2, 2007 - Just the same way as you would pass a pointer to another variable, just that in this case, you're passing a pointer to an array. What you want is the following: ... Please note that I've chosen to pass the number of options as an argument to the function, since myOptions is a pointer itself, sizeof(myOptions) would only return 4 which gives no indication about the number of elements. You can also wrap it all into one structure, like this: ... and then only pass the structure as parameter.
Find elsewhere
Top answer
1 of 3
2

As coded, printer takes a string and prints every final substring. You pass *words, which is the same as words[0], ie: the first string in the 2D array.

To pass a pointer to the array, the type of the argument should be char array[][10](*).:

#include <stdio.h>

char words[][10] = { "madam", "Russia", "India", "Japan", 
                     "China", "Brazil", "Mexico" };
int size = sizeof(words) / sizeof(words[0]);

void printer(char words[][10], int len);

int main() {
    printer(words, size);
    return 0;
}

void printer(char words[][10], int len) {
    for (int i = 0; i < len; i++) {
        printf("%s\n", array[i]));
    }
}

Note however that you could also define array as an array of pointers to character strings char *array[]. This would allow for strings of any length, not limited to 9 characters plus a null terminator.

The code would be changed to this:

#include <stdio.h>

char *words[] = { "madam", "Russia", "India", "Japan", 
                  "China", "Brazil", "Mexico" };
int size = sizeof(words) / sizeof(words[0]);

void printer(char *words[], int len);

int main() {
    printer(words, size);
    return 0;
}

void printer(char *words[], int len) {
    for (int i = 0; i < len; i++) {
        printf("%s\n", array[i]));
    }
}

The array words is initialized from string literals, which must not be changed, so it would be better to define it as const char *array[] and modify printer accordingly. Note also that printf("%s\n", array[i])) is equivalent to puts(array[i]) (good compilers detect this equivalence and generate the call to puts in both cases):

#include <stdio.h>

const char *words[] = { "madam", "Russia", "India", "Japan", 
                        "China", "Brazil", "Mexico" };
int size = sizeof(words) / sizeof(words[0]);

void printer(const char *words[], int len);

int main() {
    printer(words, size);
    return 0;
}

void printer(const char *words[], int len) {
    for (int i = 0; i < len; i++) {
        puts(array[i]);
    }
}

(*) The function does not receive an actual 2D array as argument, but a pointer to the array of arrays, which technically has type char (*)[10] but the compiler will accept both syntaxes equivalently and char array[][10] is simpler and more readable

2 of 3
1

You are just printing the 1st element of words[0], because you have passed words[0] which is equivalent to *words.

Also, to print the whole array of pointers, you need char [][10] as your parameter in function printer().

Note: You can put printer() function above main() function, then there will be no need for forward declaration.

Final Code

#include <stdio.h>

char words[][10] = {"madam", "Russia", "India", "Japan", "China", "Brazil", "Mexico"};
int size = sizeof(words) / sizeof(*words);

void printer(const char array[][10], int len){
    for(int i = 0; i < len; i++){
        puts(array[i]);
    }
}

int main(void) {
    printer(words, size);
    return 0;
}
๐ŸŒ
Quora
quora.com โ€บ How-do-I-pass-an-array-of-characters-as-a-parameter-to-a-function-C-language
How to pass an array of characters as a parameter to a function (C language) - Quora
Answer (1 of 10): AFAIK there are two ways, * if you know the size of array in advance, you can do something like this [code]void function(char array[10]) { } int main() { char array[] = {'a', 'b', ..., 'j'}; function(array) } [/code] * if not, you can do something like this [code]void fu...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ cprogramming โ€บ c_passing_arrays_to_functions.htm
Passing Arrays as Function Arguments in C
If you want to pass an array to a function, you can use either call by value or call by reference method. In call by value method, the argument to the function should be an initialized array, or an array of fixed size equal to the size of the ...
Top answer
1 of 4
1
char array_slave_1[128][128]

This is 2-dimensional array of char as paramter:

int array_length(char *a[])

This is array of pointers to char (which might be C strings, but could be other char/byte buffers, or single chars too). Except because it is a function parameter, it really is pointer to pointer, so if you are a novice you'd be better off writing what it really is, to avoid getting confused:

int array_length(char **a)

Types of array_slave_1 and a are fundamentally different, and incompatible.


If you want to make your function take the array as parameter, you could do:

int array_length(char a[][128])

which is same as this (note the extra () compared to code in question, they matter!), because array parameters really are pointers, so you have a pointer to one or more char[128] buffers:

int array_length(char (*a)[128])

Then you need a different way to determine the array length, though. Perhaps empty string means end of strings? That's up to you, really.


Alternative is to change your array to be array of pointers:

char *array_slave_1[128]; // 128 pointers to char buffer or C string
// remember that you must allocate the space of each string!
2 of 4
0

Perhaps you are just "over complicating" things.

Here is a "best guess" at what you might be trying to achieve (based on allocating room for 128x strings, each up to 127 bytes (plus a null terminator.)

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

int main() {
    char array_slave_1[ 128 ][ 127 + 1 ]; // notation helps signify this is a string

    strcpy( array_slave_1[ 0 ], "Hello World!" );
    strcpy( array_slave_1[ 1 ], "Foobar" );

    for( int i = 0; i < 2; i++ )
        printf( "'%s' length %d\n", array_slave_1[ i ], strlen( array_slave_1[ i ] ) );

    return 0;
}

Output

'Hello World!' length 12
'Foobar' length 6

strlen() has already been done in the standard C library.

๐ŸŒ
C For Dummies
c-for-dummies.com โ€บ blog
Passing Strings to a Function | C For Dummies Blog
August 21, 2021 - The output() function specifies array notation in its argument list. This notation is used throughout the function, which should be easy to understand for all C programmers. ... #include <stdio.h> void output(char *a) { int x = 0; while( *(a+x) ) { putchar(*(a+x)); x++; } putchar('\n'); } int ...
๐ŸŒ
Programiz
programiz.com โ€บ c-programming โ€บ c-arrays-functions
Pass arrays to a function in C | Programiz
June 27, 2022 - Before we learn that, let's see how you can pass individual elements of an array to functions. Passing array elements to a function is similar to passing variables to a function. #include <stdio.h> void display(int age1, int age2) { printf("%d\n", age1); printf("%d\n", age2); } int main() { int ageArray[] = {2, 8, 4, 12}; // pass second and third elements to display() display(ageArray[1], ageArray[2]); return 0; } ... Here, we have passed array parameters to the display() function in the same way we pass variables to a function.
๐ŸŒ
Coddy.Tech
coddy.tech โ€บ learn โ€บ courses โ€บ functions in c โ€บ array as a parameter
Array as a Parameter โ€“ Functions in C | Coddy
... #include <stdio.h> // Function ... printArray(a); return 0; } ... Note: When we deal with strings, we explicitly need to use the asterisk (*) to tell the compiler that each string (e.g., "Java") is an element of the arr...
๐ŸŒ
Rip Tutorial
riptutorial.com โ€บ creating arrays of strings
C Language Tutorial => Creating Arrays of Strings
This means that we can modify the pointers in the array, but we cannot modify the strings they point to. In C, the parameter to main argv (the array of command-line arguments passed when the program was run) is an array of char *: char * argv[].