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));
}
}
You're passing a variable of type
char *[]
, i.e. an array of pointers tochar
to a function expectingchar *
, i.e. a pointer to char. Also, inside ofprintNames
, you're passing a singlechar
toprintf
when the%s
format specifier expects achar *
. 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 toprintf
.