0

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)
bhatnaushad
  • 372
  • 1
  • 2
  • 16

1 Answers1

2

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?

Andrew Cottrell
  • 3,312
  • 3
  • 26
  • 41