Home > Net >  C passing char array to a function and pointers
C passing char array to a function and pointers

Time:10-14

So, I'm having a difficult time wrapping my head around using arrays and pointers in functions. I want to print the following array of chars using a function. I can print them outside the function with the for loop but when I pass the same code to the function, the function returns NULLS. Could I get some insight on this?

#include <stdio.h>

void printNames(char arr[], int size);

int main()
{
    
    char *names[4] = {"Bruce", "Clark", "Barry", "Diana"};

    //changed a typo
    for(int i = 0; i < 4; i  )
    {
        printf("%s ", *(names   i));
    }

    printNames(names, 4);

    return 0;


}

void printNames(char arr[], int size)
{
    for(int i = 0; i < size; i  )
    {
        printf("%s ", *(arr   i));
    }


}

CodePudding user response:

You're passing a variable of type char *[], i.e. an array of pointers to char to a function expecting char *, i.e. a pointer to char. Also, inside of printNames, you're passing a single char to printf when the %s format specifier expects a char *. Your compiler should have warned you about both of these.

You need to change the definition of printNames to have the parameter type match what is passed in and to match what you want to pass to printf.

void printNames(char *arr[], int size);
  • Related