I'm trying to copy the individual elements of argv
into a 2nd array. I'm using strncpy
to do it.
Here's a stripped version that replicates the problem.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
printf("%d\n", argc);
char *argvarray[argc];
int arrlen;
//int j;
for(int j=0; j< argc; j++){
arrlen = arrlen + strlen(argv[j]);
}
printf("size of argv: %d\n", arrlen); //see if size is right
strncpy(*argvarray, *argv, arrlen);
for(int j=0; j< argc; j++){
printf("value of j: %d\n", j); //to see what's going on
printf("%s\n", argv[j]);
printf("%s\n", argvarray[j]); //gets 1st element no problem
}
return 0;
}
If I pass 1 arg to main it copies the first element of argv
to argvarray
but the second is not copied. If I pass more than 1 arg it segfaults on strncpy()
.
Why is this happening? What's the best way to copy all elements of a char array (particularly char arrays declared in function definitions) to other char arrays without knowing the size before hand, as in the case of argv
?