0

Is there any way to loop array of character pointers? I was able to get the number of items in **args but how to get number of its each element so we can print its characters. As we can see each element column dimension differs. So is there any way in C to loop this?

int main()
{
    
    char *argv_c1[3] = {"cat","f.txt",NULL};
    char *argv_c2[2]={"sort",NULL};
    char *argv_c3[2]={"uniq",NULL};
    char *argv_c4[3]={"grep","day",NULL};
    char *argv_c5[3]={"wc","-l",NULL};

    char **args[]={argv_c1, argv_c2, argv_c3, argv_c4, argv_c5};

    unsigned long int total = sizeof(args)/sizeof(args[0]);
    printf("ld\n",total);
    
    for(int i=0;i<total;i++)
    {
        //how to loop argv_c1, argv_c2 ... argv_c5 ?
    }


    return 0;
}
2
  • Have you verified that total is what you expect? Commented Mar 29, 2022 at 15:54
  • 1
    @ScottHunter Why would it not be? However, for the elements of args, you can no longer use such syntax, because they're just pointers: each of the argv_c* arrays will have decayed into a pointer. The term, "decay", is used because information has been lost - that info is the array's size. Commented Mar 29, 2022 at 15:58

1 Answer 1

1

This will loop over the elements of args[i]:

for(int j=0; args[i][j]!=NULL; j++)
Sign up to request clarification or add additional context in comments.

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.