How to find the length of argv[] in C

左心房为你撑大大i 提交于 2019-11-29 03:43:46
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.

Not sure why no one has suggested changing strlen to refer to a specific entry in the array of pointers to char?

 strlen(argv[0])     // also, 1, 2, up to (argc - 1)

Also, http://www.cdecl.org/ helps in confirming that the char *argv[] statement is: declare argv as array of pointer to char

int count = 0; 
while(argv[++count] != NULL);

Now, count will have the length of argv

user1787351

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.

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

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;
}

?

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
}
//Task = get length of argv
    string text=*argv; //assigning charValue to string variable "text"
    int l=text.length(); //getting the length of the string & assigning to variale "l"

    //this loop just outputs result on the screen
    for (int i=0; i<l; i++) { 
        cout << *(*argv+i) << flush;
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!