int main(int argc, char **argv){
char Q[MAXCHAR];
Q=argv[k+1];}
Q is an array while argv[k+1] is a pointer. How can I get the content of argv[k+1] into Q?
int main(int argc, char **argv){
char Q[MAXCHAR];
Q=argv[k+1];}
Q is an array while argv[k+1] is a pointer. How can I get the content of argv[k+1] into Q?
You can use snprintf
snprintf(Q, MAXCHAR, "%s", argv[k]);
(edited : first version recommended strncpy).
You can't directly assign Q = argv[k+1]
. For an array (Q[MAXCHAR]
), arrayname (Q
) is the base address. The base address of an array can't be changed.
Assuming k = 0
, you can use any of the following to get the argv[1] data into Q.
memmove(Q, argv[1], strlen(argv[1]) + 1);
or
snprintf(Q, strlen(argv[1]) + 1, "%s", argv[1]);
or
strncpy(Q, argv[1], strlen(argv[1]) + 1);
or
memcpy(Q, argv[1], strlen(argv[1]) + 1);
or
sprintf(Q, "%s", argv[1]);
or
strcpy(Q, argv[1]);
Here is the program and it's output using memmove:
#include <stdio.h>
#include <string.h>
#define MAXCHAR 20
int main(int argc, char **argv)
{
if (argc < 2) {
puts("Not enough arguments");
return -1;
}
char Q[MAXCHAR] = {0};
memmove(Q, argv[1], strlen(argv[1]) + 1);
puts(Q);
return 0;
}
Output:
me@linux:~$ ./a.out stackexchange
stackexchange