0

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


}
  • 3
    `names` is an array of four pointers to `char`, i.e. `char *[4]`. The `printNames` argument `arr` is a pointer to `char`, i.e. `char *`. – Some programmer dude Oct 13 '21 at 16:01
  • 1
    Also remember (or learn) that for any pointer or array `arr` and index `i`, the expression `*(arr + i)` is *exactly* equal to `arr[i]`. The latter (`arr[i]`) is not only easier to read and understand, but also less to write. – Some programmer dude Oct 13 '21 at 16:02
  • Also, `for(int i = 0; i < 15; i++)`? That will make you print 15 elements of the four-element array... And lead to *undefined behavior* as you go out of bounds. – Some programmer dude Oct 13 '21 at 16:03
  • Lastly, you initialize `names` using only *one* string, all the remaining three elements will be null pointers. Which you dereference and again have *undefined behavior*. – Some programmer dude Oct 13 '21 at 16:03
  • You cannot pass an array to a function in C (unless you wrap it in a struct). You can only pass a pointer to the first element of the array. – William Pursell Oct 13 '21 at 16:17
  • 2
    Save time, enable all warnings as `void printNames(char arr[], int size); char *names[4] = ... printNames(names, 4);` is a problem. Faster feedback than stackoverflow. – chux - Reinstate Monica Oct 13 '21 at 16:17

1 Answers1

0

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);
dbush
  • 205,898
  • 23
  • 218
  • 273