0

I have a dynamic array of c-strings

char **my_strings = (char**)malloc(50 * sizeof(char*));

and I want to find it's actual length (how many strings it actually contains). How can I do this?

12
  • 5
    Pass the size, or NULL-terminate the array, or both. Commented Mar 21, 2017 at 20:24
  • Read How to Ask and fdollow the advice. Provide a minimal reproducible example. Commented Mar 21, 2017 at 20:24
  • You don't have an array of c-strings. You have a pointer to pointers of char. While similar, not the entirely same thing. Commented Mar 21, 2017 at 20:25
  • @StoryTeller I tried to do this, but it doesn't work : while (!strings[count] == NULL) count++; Commented Mar 21, 2017 at 20:25
  • 1
    @StoryTeller Oh yes. C has something for every coding style in its long history. argv[argc] is NULL C11 §5.1.2.2.1 2, C also set the last element to NULL. Is that redundant? Did I ask that before? Courtesy of department of redundancy department ;-) ;-) Commented Mar 21, 2017 at 21:05

3 Answers 3

3

You can't tell: it's your job to keep track of the size, or to use a magic value (NULL, say) to mark the final element.

Note that the c runtime probably keeps track of the amount of memory allocated, but this is not exposed to you in any portable way.

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

Comments

2

Make the array be terminated with a NULL pointer, then just do:

size_t count = 0;
while (my_strings[count] != NULL) {
    ++count;
}

Comments

0

A char * is not a "string": it is a pointer. Strings are arrays where one of its elements is '\0'.

Pointers and arrays are different!

Check section 6 of the c-faq.

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.