0

Basically I have an array of words

 void print(char *str) {
 cout << str <<endl;
 }

 int main() {
 int i =0;
 char* name[] = {"Fred", "John", "Jimmy"};
 print(*name[0]);
 }

I would like to pass only first word to a function, but when I am doing in a way as I am doing right now it passes all the names.

Fred
  • 4,894
  • 1
  • 31
  • 48
inside
  • 3,047
  • 10
  • 49
  • 75

2 Answers2

4

You have an extra dereference there, the code should be like this:

print(name[0]);

Ideally, your print function should take const char*, because it does not modify the strings passed in.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

char* name[] is an array of pointers to char, typically strings.

void print(char *str) requires a single pointer to a char as an argument.

By calling print(*name[0]), you are actually taking the first pointer from your name[] array, and dereferencing it to turn it into a single char. Since your function requires a pointer to char, you simply need to call it with print(name[0]) and you'll get the first item in your array.

Fred
  • 4,894
  • 1
  • 31
  • 48