Reputation: 107
I'm new to C-programming. I wrote a function
void fun (char** argv, int count, int loc);
In my function, I tried to create another array by doing
char** newray=strdup(argv).
When I tried to execute:
printf(newray[0])
I got a segmentation fault. I fixed it by doing
printf("%s\n", newray[0]).
However, to output the argv[0]
, I only need to do this:
printf(argv[0]).
What is the reason behind it?
Upvotes: 1
Views: 360
Reputation: 12795
This is because argv
is not a string, it is an array of strings, so strdup is not a correct function to copy it. You need to do something along the lines of:
newray = malloc(sizeof(char*) * argc);
for (size_t i = 0; i < argc; ++ i) newray[i] = strdup(argv[i]);
Where argc
is the number of elements in argv
. You will also need to free all the elements and then the array itself when you are done with it.
Upvotes: 1