0

I have a function of that takes array of strings as input, add strings if its empty and then return the array. If the array is not empty, the array's content should be displayed.

If condition checks for emptiness by checking the size. My problem is that the size is always zero even when the array is not empty. And I know the array is not empty because I can print out its content.

This is my code:

 char **check(char **words) {
        if(sizeof (words) / sizeof (**words) == 0) {
            words[0] = "vacation";
            words[1] = "vaccaciones";
            words[2] = "vancances"
        }
        else {
             //do something else
        }
 }

It never goes into the else condition no matter what I try to do. I checked the array, it's not empty and the value for my if condition is always zero. What am I doing wrong?

user2162882
  • 61
  • 1
  • 8
  • 3
    This could probably be considered a duplicate of http://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c/10349610#10349610 – Bill Lynch Jan 31 '15 at 04:57
  • 1
    @user2162882: Your approach is doomed to failure. There is no way using `sizeof()` to determine how many elements `words` is pointing to. Either pass the size as another parameter or add some sentinel value to mark the end of the array. See Rob's answer or the link in Bill Lynch's comment. – Blastfurnace Jan 31 '15 at 05:17

2 Answers2

3
sizeof (words) / sizeof (**words)

words is a pointer to pointer and sizeof(pointer)/sizeof(element) is what you are getting. So you get

sizeof(pointer) = 4 /* Assuming */
sizeof(element)  = 1

The result will be 4/1 != 0 so the if() condition never passes.

Your check has got nothing to do with the contents/size of your array.

Gopi
  • 19,784
  • 4
  • 24
  • 36
  • But the if condition passes, it's else that doesn't. – user2162882 Jan 31 '15 at 05:07
  • @user2162882 This is what happens with your division please check the values to see how you are getting zero I can't figure out how this will be 0 with the shown code – Gopi Jan 31 '15 at 05:12
2

The technique for checking number of elements in an array is sizeof(array)/sizeof(*array). You have an extra asterisk (assuming you want to check the number of pointers in an array of pointers passed).

Second, that technique does not work on pointers. Passing an array to a function converts it to a pointer (containing the address of the first element) and it is not possible to retrieve the number of elements of an array from such a pointer.

If you want a function to access the size of the array you need to pass the size in some some other way (for example, as an additional argument to the function).

Rob
  • 1,966
  • 9
  • 13