Search code examples
csegmentation-faultprogram-entry-pointargvargc

Why isn't argc same as strlen(argv[i])?


Why does my code give segmentation fault when I use strlen(argv[i]) instead of argc?

#include<stdio.h>
#include<ctype.h>
#include<string.h>

int main(int argc , char* argv[])
{
    for(int i=0;i<strlen(argv[i]);i++)
    printf("%s\n",argv[i]);
    return 0;
}

The output is

./a.out
hello
world
Segmentation fault (core dumped)

Solution

  • Use argc:

    int main(int argc , char* argv[])
    {
        for(int i = 0; i < argc; i++)
            printf("%s\n", argv[i]);
        return 0;
    }
    

    For more information, see the answer to this question: What does int argc, char *argv[] mean?