cargvstrlenstrcat

How to find the length of argv[] in C


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

int main(int argc, char *argv[]){
    int fir; //badly named loop variable
    char *input[] = calloc( strlen(argv), sizeof(char)); //initializing an array
    for( fir = 1; fir< strlen(argv); fir++){ //removing the first element of argv
        strcat(input, argv[fir]); // appending to input
    }
}

The error I'm getting is for line 7. It says "passing argument 1 of 'strlen' from incompatible pointer type". I get the same error for the strcat function. It also says "given a char ** but expected a const char *" for both functions.

I'm trying to populate a new array with all the elements of argv except the first. I tried argv = &argv[1] and it did not work.

Do the strlen() and strcat() functions not take char arrays?


Solution

  • int main(int argc, char *argv[])
    

    argv is an array of pointers to char (i.e. array of strings). The length of this array is stored in argc argument.

    strlen is meant to be used to retrieve the length of the single string that must be null-terminated else the behavior is undefined.