0

I'm trying to pass an array of char * defined with braces and with static strings, and I want to pass it as an argument to a function.

The array is the next:

char * phrase[] = {"my", "name", "is", "John"};

and the function which is going to receive the argument is implemented as follows:

void composeList(char * phrase[]){
  //I'm getting the size of the list
  int phrase_list_size = sizeof(*phrase)/sizeof(phrase[0]);
  printf("%d\n",phrase_list_size);
}

I call that function in this way:

composeList(phrase);

But when I print the size the value is 1 instead of 4. Could you help me?

Marco
  • 670
  • 5
  • 16
  • An array decays into a pointer when is passed to a function, and thats what you get inside the function: the size of a pointer. – David Ranieri May 10 '17 at 16:09
  • @Fredrik both values are 4 on a 32bit system or 8 on a 64bit system. – mch May 10 '17 at 16:30
  • I want to know the number of items. sizeof(*phrase) returns the number of chars in the array. I obtained the operation from a Stackoverflow post. And it runs when i do that in the main functions. – Marco May 10 '17 at 17:24
  • Use a function like this: `void composeList(char * phrase[], size_t size);` and call it like this: `composeList(phrase, sizeof(*phrase)/sizeof(phrase[0]));` – Erik W May 10 '17 at 19:55
  • Another tip is to use always use `-Wall` and `-Wextra` when compiling. In this case it will warn about your problem – Erik W May 10 '17 at 19:57

0 Answers0