If I have char **args
how can I loop through the rows of the array to determine how many there are?
For example, if char **args == {"one", "two", "three"}
, how can I loop through each element, keeping count, and then return 3?
If I have char **args
how can I loop through the rows of the array to determine how many there are?
For example, if char **args == {"one", "two", "three"}
, how can I loop through each element, keeping count, and then return 3?
Since your args
is null-terminated, simply write
int i;
for (i = 0; args[i]; i++)
// do something
You can get the size at compile time as shown below.
This is one way to iterate over the array of strings.
char* args[] = {"one", "two", "three"};
char** p = args;
size_t len = sizeof(args) / sizeof(*args);
for (int i = 0; i < len; ++i) {
printf("item %u = %s\n", i, *p++);
}
[EDIT]
I misunderstood, it seems you mean args on the command line (which is null terminated);
In which case you could use:
int main(int argc, char** argv) {
char** p = argv;
int count = 0;
while (*p)
printf("item %u = %s\n", count++, *p++);
}
or even
int main(int argc, char** argv) {
int count = 0;
while (*argv)
printf("item %u = %s\n", count++, *argv++);
}
Note you will print argv[0] in the above case. Adapt to your needs.
Of course in this case you also have argc so you can iterate until i < argc. Your question is not clear. You should provide full buildable code in your question.
Try the following code:
int count=0;
while(*args++)count++;
printf(" %d\n",count);
while loop should terminate when it reaches the end of the string array, however it would be better to have:
char strAry[M][N]="…your initialization…";
**args;
args=strAry;