#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?
The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element.
Bookmark this question. Show activity on this post. He said the memory size of argv in int main(int argc, char **argv) is 48 bytes, including itself.
The argc parameter represents the number of command line arguments, and char *argv[] is an array of strings (character pointers) representing the individual arguments provided on the command line.
Command-line Arguments: main( int argc, char *argv[] ) Here argc means argument count and argument vector. The first argument is the number of parameters passed plus one to include the name of the program that was executed to get those process running.
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*
. 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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With