Saturday, 25 July 2015

POINTER TO A STRING, STRUCTURE ,

Pointer to array of string in c programming

Pointer to array of string: A pointer which pointing to an array which content is string, is known as pointer to array of strings.


What will be output if you will execute following code?

#include<stdio.h>
int main(){

char *array[4]={"c","c++","java","sql"};
char *(*ptr)[4]=&array;
printf("%s ",++(*ptr)[2]);

return 0;
}

Output: ava
Explanation:

In this example

ptr: It is pointer to array of string of size 4.

array[4]: It is an array and its content are string.
Pictorial representation:






Note: In the above figure upper part of box represent content and lower part represent memory address. We have assumed arbitrary address.

++(*ptr)[2]
=++(*&array)[2] //ptr=&array
=++array[2]
=++”java”
=”ava” //Since ptr is character pointer so it
// will increment only one byte

Note: %s is used to print stream of characters up to null (\0) character.

Pointer to structure in c programming



Pointer to structure: A pointer which is pointing to a structure is know as pointer to structure. 


Examples of pointers to structure:

What will be output if you will execute following code?


#include<stdio.h>

struct address{
char *name;
char street[10];
int pin;
}cus={"A.Kumar","H-2",456003},*p=&cus;

int main(){

printf("%s %s",p->name,(*p).street);


return 0;
}

OutputA.Kumar H-2
Explanation:

p is pointer to structure address.
-> and (*). Both are same thing. These operators are used to access data member of structure by using structure’s pointer.


No comments:

Post a Comment