The command line pointer char *argv [] used in C language allows operations such as;
ptintf ("%c", argv [3][6]); // to print the 7th element of 4th argument
printf ("%s", argv [3]); // to print the 4th parsed argument
Now I understand that argv char array is created before main function is called and it char *argv [] is merely a pointer directing towards that array created by the compiler.
How can we create a pointer in C code, which would allow similar operations?
I tried doing,
#include <stdio.h>
int main() {
char array [20] [20];
char *ptr_array = array ;
array [0] [0]= 'a';
array [0][1]= 'b';
array [0] [2] = '\0';
array [1] [0]= 'a';
array [1][1]= 'b';
array [1] [2] = '\0';
array [2] [0]= 'a';
array [2][1]= 'b';
array [2] [2] = '\0';
// assuming there is content in the array
printf("%s\n", ptr_array [1]);
return 0; }
but I end up with a warning upon compilation and a core dump upon execution.
ptr_arrayis a pointer-to-char. I don't see what it's doing in your code. You want either a two-dimensional array (which you have, it'sarray), or a pointer-to-pointer (which in realityargvis). Just removeptr_arrayfrom the code and usearrayinstead.printf("%s\n", array[1]);should work fine. (Also, it seems you are confusing strings and individual characters – please read a basic tutorial on C strings and characters, and also read the man page forprintf().)int. Neither doesargv, since it's not an array, it's a pointer-to-pointer. And we are using it like this because the language specification says so (it's the most practical way of getting command line arguments, since their length is unknown at compile time, so one can't really say thatargvshould be a pointer to array of known size.)