Ricky Hewitt
Ricky Hewitt

Reputation: 518

C: Iterate through an array of strings

I'm currently learning C and am struggling with how to iterate through an array of strings.
Let's just say I define an array, like so:

char* argv_custom[] = {"--debug", "--verbose", "--test", "--ultimate"};

Now, how would I go about determining the number of strings within argv_custom? (e.g. argc_custom)
Am I going the right way about this in the first place? Also, is it possible to do something like:

Pseudocode

if ('--debug' in argv_custom) { // do stuff }

Upvotes: 3

Views: 8254

Answers (3)

Jens Bodal
Jens Bodal

Reputation: 1757

I've had this question quite a few times and from what I've found my favorite solution is to just iterate through the pointer until null. sizeof stops working as soon as you start using functions and passing the arrays around.

Here's a paradigm I've used time and time again in my assignments and it's been really helpful. The exact same thing can be used for getting the length of a cstring or iterating through its characters.

char* argv_custom[] = {"--debug", "--verbose", "--test", "--ultimate"};
char **temp = argv_custom;
int size = 0;
while (*temp) {
    ++size;
    ++temp;
}

This is not preferred over using sizeof, however it's an alternative when you want to loop through it.

Upvotes: -1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272507

Now, how would I go about determining the number of strings within argv_custom?

The canonical way:

int argc_custom = sizeof(argv_custom) / sizeof(argv_custom[0]);

Note: This only works on the array itself, as soon as you have a pointer (such as if you pass argv_custom to a function), it no longer works:

char **p = argv_custom;
int argc_custom = sizeof(p) / sizeof(p[0]);  // No me gusta

is it possible to do something like: ...

There's no shortcut. You would have to iterate over each string, and do strcmp. Of course, you could (and probably should) wrap this behaviour into a function.

Upvotes: 11

Jack
Jack

Reputation: 133577

you can do sizeof(argv_custom)/sizeof(argv_custom[0]). This calculates the total length of the array divided by the size of every single element.

Upvotes: 3

Related Questions