C Language

Pointer Function Arrays String

In C Language by Baqir AliLeave a Comment

Pointers are often passed to a function as arguments

  • This allows data items within the calling part of the program to be accessed by the function, altered within the function, and then passed back to the calling portion of the program in altered form.
  • This use of pointers is referred to as passing arguments by reference, rather than by value.
void swap(int *p, int *q)
{
	int temp;
	temp = *p;
	*p = *q;
	*q = temp;
}
temp = *p; 

 The variable temp is assigned the int pointed to by p.

*p = *q;

The object pointed to by p is assigned the int pointed to by q. 

*q = temp;

  The object pointed to by p is assigned the value temp.

Pointers and Arrays

We reference array elements with such notations as table[x][y]. As it turns out this array notation really nothing more than a thinly distinguished form of pointer notation, In fact, the compiler translates array notation into pointer notation when compiling, since the internal architecture of the microprocessor understand pointers but does not understand arrays.

Example : Array Notation

void main(void)
{
		int nums[ ]= { 92, 81, 70, 69, 58 };
		int index;

		for(index=0; index<5; index++)
		    printf(“ %d \n”, nums[index]);
		
		getch();
}
Array Notation
Array Notation

Example : Pointer Notation

void main(void)
{
		int nums[ ]= { 92, 81, 70, 69, 58 };
		int index;

		for(index=0; index<5; index++)
		    printf(“ %d \n”, *(nums+index);

		getch();
}

Pointer Notation
Pointer Notation

Pointers and Strings

Since arrays are closely connected with pointers, Someone might expect that strings and pointers are closely related, and this is correct. Many of the C library functions that work with strings do so by using pointers.

void main(void)
{
	char *salute = “Greetings”;
	char name[21];
	puts(“Enter Your Name : ”);
	gets(name);
	puts(salute);
	puts(name);
}
pointer string
pointer string

Array of Pointers to String

There is another difference between initializing a string as an array or as a pointer. This difference is most easily seen when we talk about an array of strings ( or if we use pointers, an array of pointers to strings).

Array of Strings.. Array version

void main(void)
{
    char list[3][8]={“Aslam”, “ Ahmed”, Akram”};
	int index;
	for(index = 0; index<3; index++)
		printf(“\n %s”, list[index]);
	getch();
}

Array of Strings… Pointer Version

void main(void)
{
    char *list[3]={“Aslam”, “ Ahmed”, “Saleem”};
	int index;
	for(index = 0; index<3; index++)
		printf(“\n %s”, list[index]);
	getch();
}

Leave a Comment