How to find the length of argv[] in C

后端 未结 8 2069
青春惊慌失措
青春惊慌失措 2020-12-15 06:41
#include 
#include 
#include 

int main(int argc, char *argv[]){
    int fir; //badly named loop variable
    char *in         


        
相关标签:
8条回答
  • 2020-12-15 06:51

    argv is an array of char, strlen only takes strings. If you want to get the length of each argument in argv (which is what I was trying to do), you must iterate through it, accessing the elements like so argv[i][j]. Using the argument argv[i][j] != '\0'. If you just want the number of arguments use argc.

    0 讨论(0)
  • 2020-12-15 06:52

    Perhaps you meant to do something like this:

    size_t argv_length(char** argv)
    {
        size_t ret = 0;
        while( *(++argv) )
            ret += strlen(*argv);
    
        return ret;
    }
    

    ?

    0 讨论(0)
  • 2020-12-15 06:53
    int count = 0; 
    while(argv[++count] != NULL);
    

    Now, count will have the length of argv

    0 讨论(0)
  • 2020-12-15 06:57

    argv takes an arryas of char* but you need to pass argc to strlen rather than whole the array. Then you wont get any error on strcat.

     #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(argc), 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
    }
    
    0 讨论(0)
  • 2020-12-15 06:58
    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.

    0 讨论(0)
  • 2020-12-15 07:05

    argv is an array of char*. The size of this array is argc. You should pass an element of this array to strlen.

    0 讨论(0)
提交回复
热议问题