csortingpointersinsertion-sort

Passing an array of structs to a function in C


I have an assignment to finish and I am getting caught up on a pointer issue. I have an array of structs that I created and want to send it to a sort function. Before I send it to the sort function I want to send it to a print function to verify that the pointer is working. Here is the code I have...

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

//------------------------------

struct Person {
    int age;
    char name[10];
};

//------------------------------

int main() {
    struct Person p1 = {26, "devin"};
    struct Person arr[] = {p1};

    int n = sizeof(arr) / sizeof(arr[0]);

    printf("--Original Array--\n");
    print(arr, n);

The error I am running into when I try to compile is

a1q4.c: In function ‘print’:
a1q4.c:24:18: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
   24 |         printf("%s ",arr[i]);
  |                 ~^   ~~~~~~
  |                  |      |
  |                  char * int
  |                 %d

I'm not sure how pointers work very well, I have tried using * in front of arr[i] but it won't work. Any ideas?


Solution

  • You could try something like this:

    #include <stdio.h>
    
    typedef struct Person
    {
        int age;
        char name[10];
    } Person;
    
    void print(Person* arr, int n)
    {
        for (int i = 0; i < n; ++i)
        {
            printf("%s ",arr[i].name);
        }
        printf("\n");
    }
    
    int main()
    {
        Person p1 = {26, "devin"};
        Person arr[] = {p1};
        
        int n = sizeof(arr) / sizeof(arr[0]);
        
        printf("--Original Array--\n");
        print(arr, n);
    }