Skip to main content
+ link for array to pointer decay.
Source Link
Edgar Bonet
  • 45.2k
  • 4
  • 42
  • 81

Just change this:

void printList(char *l, int x) {

to this:

void printList(char **l, int x) {

OK, this deserves some explanation...

In C and C++, when you use (not when you define) an array identifier, it decays to a pointer to its first elementdecays to a pointer to its first element. In this this case,

char *list[3] = {};

is an array of pointers to char. When you use it here:

printList(list, 3);

it decays to a pointer to pointer to char. Thus the double * needed in the parameter declaration.

Side note: to get really correct C++, you should replace every instance of char by const char. This is because the characters in question belong to string literals, and you are not allowed to modify a string literal at run time.

Just change this:

void printList(char *l, int x) {

to this:

void printList(char **l, int x) {

OK, this deserves some explanation...

In C and C++, when you use (not when you define) an array identifier, it decays to a pointer to its first element. In this case,

char *list[3] = {};

is an array of pointers to char. When you use it here:

printList(list, 3);

it decays to a pointer to pointer to char. Thus the double * needed in the parameter declaration.

Side note: to get really correct C++, you should replace every instance of char by const char. This is because the characters in question belong to string literals, and you are not allowed to modify a string literal at run time.

Just change this:

void printList(char *l, int x) {

to this:

void printList(char **l, int x) {

OK, this deserves some explanation...

In C and C++, when you use (not when you define) an array identifier, it decays to a pointer to its first element. In this case,

char *list[3] = {};

is an array of pointers to char. When you use it here:

printList(list, 3);

it decays to a pointer to pointer to char. Thus the double * needed in the parameter declaration.

Side note: to get really correct C++, you should replace every instance of char by const char. This is because the characters in question belong to string literals, and you are not allowed to modify a string literal at run time.

Source Link
Edgar Bonet
  • 45.2k
  • 4
  • 42
  • 81

Just change this:

void printList(char *l, int x) {

to this:

void printList(char **l, int x) {

OK, this deserves some explanation...

In C and C++, when you use (not when you define) an array identifier, it decays to a pointer to its first element. In this case,

char *list[3] = {};

is an array of pointers to char. When you use it here:

printList(list, 3);

it decays to a pointer to pointer to char. Thus the double * needed in the parameter declaration.

Side note: to get really correct C++, you should replace every instance of char by const char. This is because the characters in question belong to string literals, and you are not allowed to modify a string literal at run time.