简体   繁体   中英

How to derive argc from **argv in C

I have an assignment where I'm not allowed to edit the main program, but to free the memory of a copy of argv. So far the only solution I've found is using argc to determine how many blocks need to be freed. However, argc is not an input into the freeing program, but a copy of argv is. Is there anyway to derive argc from **argv?

This should do the trick:

#include <stdio.h>

int main(int argc, char ** argv){
    int count = 0;

    for(int i = 0; 1; i++)
        if(argv[i] == 0) break;
        else count++;

    printf("Argc: %d\n", count);
}

Or in a compact way (thanks to chqrlie ):

#include <stdio.h>

int main(int argc, char **argv) {
    int count;
    for (count = 0; argv[count] != NULL; count++)
        continue;
    printf("Argc: %d\n", count);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM