In: Computer Science
Modify the following code to use ONLY pointer arithmetic (no array expressions) and no for loops to do the same thing this code does. Be sure that you understand how the code works and how the pointer arithmetic relates to the array expression form. Provide liberal comments to explain what your pointer arithmetic is computing.
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{ int arg_count = 0;
for (arg_count = 0; arg_count < argc; arg_count++)
printf("%s\n", argv[arg_count]);
}
Here, We have used the double pointer to give the command line arguments. so instead of array expression which is shown in printf line, we can use pointer expression to do the same thing.
Here what the code does : when you are running the file and entering your executable file with command line arguments, It will print all the arguments including filename also.
Eg. If your executable file name is MyFile and you are running that from CMD like this:
INPUT : MyFile Argument1 Argument2 and after enter you will see the following output like:
OUTPUT:
MyFIle
Argument1
Argument 2
So, Here I am writing the same code without array expression:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
.// argc contain the number of argument provided by the user.
Here above has 3 arguments. So argc will be 3. and It has been
decresing till it reaches to 0. so in our case this loop will
execute 3 times.
while(argc-- > 0){
// Now here we have **argv. which contains the address of first command line argument. while *argv will contain the value at that address. which is first command line. so now *argv++ will be increment in address(**).
so FIrst It will print the first argument after that all the
arguments.
printf("%s\n",*argv++);
}
}