简体   繁体   English

如何从C中的** argv派生argc

[英]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. 我有一项作业,不允许我编辑主程序,但要释放argv副本的内存。 So far the only solution I've found is using argc to determine how many blocks need to be freed. 到目前为止,我发现的唯一解决方案是使用argc确定需要释放多少块。 However, argc is not an input into the freeing program, but a copy of argv is. 但是,argc不是释放程序的输入,而是argv的副本。 Is there anyway to derive argc from **argv? 反正有从** argv派生argc吗?

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 ): 或以一种紧凑的方式(由于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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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