Printing strings from an array in a function in C

I continue to crash in case 4 of my switch in my main function and cannot fix it.

I will explain the code a bit and hope you guys can help me:

Function initialization

void function1(char[]);

String array declaration

const char *my_array[] = {
"Array of strings one",
"Array of strings two",
"Array of strings three"};

Quoting over an array of strings in the main function (this works correctly, it prints an array of strings)

int i;
for (i=0; i < 3; i++) {
    printf("%s\n", my_array[i]);
}

Code in switch function (still in main function)

case 4:
            function1(my_array);
            break;

I tested, and all the previous code works correctly, the problem is here (outside the main function):

void function1(char my_array[]) {
for (i=0; i < 3; i++) {
    printf("%s\n", my_array[i]);
}
printf("\n");}

When I run case 4 of the switch, it fails.

Warning 2: log

warning: passing argument 1 of 'function1' from an incompatible pointer Type

warning: format '% s' expects an argument of type 'char *', but argument 2 is of type 'int' [-Wformat =]

, , , .

, , , , !

+4
4

,

: 1 'function1'

: , , .

:

warning: format '% s' 'char *', 2 'int' [-Wformat =]

C, char *.

, , , - function1:

void function1(const char *my_array[])
//             ^^^^^      ^

, const my_array main.

* , int, char, printf , . char int s.

+9

void function1 (char my_array [])

char, ( ). ,

printf("%s\n", my_array[i]);

my_array [i], "i" % s ( ). ,

printf(%c\n", my_array[i]);

, , char ( OR)

void function1(const char* my_array[])
{
    for (size_t i = 0; i < 3; i++)
    {
        printf("%s\n", my_array[i]);
    }
    printf("\n");
}

'const' ( / ). , .

void function1(const char* my_array[], size_t n)
{
    for (size_t i = 0; i < n; i++)
    {
        printf("%s\n", my_array[i]);
    }
    printf("\n");
}
+1

, , , "const" , " ".

, , ( *).

:

void function1(char[]);

:

void function1(char*[]);

:

    void function1(char my_array[]) {
    for (i=0; i < 3; i++) {
    printf("%s\n", my_array[i]);
    }
    printf("\n");
}

:

    void function1(char* my_array[]) {
    for (i=0; i < 3; i++) {
    printf("%s\n", my_array[i]);
    }
    printf("\n");
}

!

, , C.

. !

+1
source

Assuming you need a function that moves through the elements of an array and prints all its contents, here is what I suggest:

#include <stdio.h>
#include <stdlib.h>


void view(char *array[]){
    int i;
    for (i = 0; i < sizeof(array)/sizeof(char); i++){ 
        //sizeof(array)/sizeof(char) = length of any array          
        printf("\nElement -> %s",array[i]);
    }
}


int main() {

    char *arr[] = {"String One", "String Two", "String Three"};

    view(arr); //Calling the function

    return 0;
}
0
source

All Articles