C Programming – Pointer to argc

InPursuitJust for fun, here’s a little program that uses a pointer to return the number of arguments that are submitted to the program at the command line.

#include <stdio.h>

int main(int argc, char argv[])
{
int *ptrArgc;

ptrArgc = &argc;
printf("\n\nOutput number of arguments in argc: %d \n\n", *ptrArgc);

printf("\n\nOutput memory address of argc: %d \n\n", ptrArgc);

return 0;

}

First, notice the line that declares the main() function in the program. The “int argc” declares an integer that automatically fills itself with the number of arguments entered at the command line when you run the program. The name of the program is the first argument, so the smallest number it can return is 1. The “char argv[]” is a character array that contains all the arguments entered at the command line, with “argv[0]” returning the name of the program itself.

The line “int *ptrArgc;” line declares a pointer and the “ptrArgc = &argc;” line assigns the memory address of argc to the pointer.

When printf() is used for the first time, ptrArgc is dereferenced with an asterisk. This causes it to print the value contained in argc instead of the memory address.

The second time printf() is used, ptrArgc is not dereferenced, so it prints the number actually contained in ptrArgc, which is the memory address that holds the value for argc.

Try compiling and running this program, entering different numbers of arguments at the command line. Notice the assigned memory address changes when you run the program.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s