#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?
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
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;
}
来源:https://stackoverflow.com/questions/18649547/how-to-find-the-length-of-argv-in-c