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?

2
  • 3
    This could probably be considered a duplicate of stackoverflow.com/questions/37538/… Commented Jan 31, 2015 at 4: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. Commented Jan 31, 2015 at 5:17

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But the if condition passes, it's else that doesn't.
@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
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.