1

Explain in a simple example. How to pass a char* to a function?

#define name1 "ABCD"
#define name2 "EFGH"
#define name3 "HIJK"

char *list[3] = {};

void printList(char *l, int x) {
  for (int i = 0; i < x; i++) {
    Serial.println(l[i]);
  }

}



void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("start");
  list[0] = name1;
  list[1] = name2;
  list[2] = name3;

  printList(list, 3);

}

void loop() {
  // put your main code here, to run repeatedly:

}

I get an error:

/home/guy/Documents/Dropbox/Arduino/sketch_jun12a/sketch_jun12a.ino: In function 'void setup()':
sketch_jun12a:24:13: error: cannot convert 'char**' to 'char*'
   24 |   printList(list, 3);
      |             ^~~~
      |             |
      |             char**
/home/guy/Documents/Dropbox/Arduino/sketch_jun12a/sketch_jun12a.ino:7:22: note:   initializing argument 1 of 'void printList(char*, int)'
    7 | void printList(char *l, int x) {
      |                ~~~~~~^
exit status 1
cannot convert 'char**' to 'char*'
2
  • You're trying to pass an array of char * to a function that is expecting a single char *. Commented Jun 12, 2022 at 16:45
  • @Majenko AFAIK anyway you pass only pointer for the first cell of the array, or am I wrong ? Commented Jun 12, 2022 at 17:03

1 Answer 1

7

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.