Pointers to Structures example program in C

By: Charles Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

To illustrate some of the considerations involved with pointers to and arrays of structures, let us write the keyword-counting program using pointers instead of array indices.

The external declaration of keytab need not change, but main and binsearch do need modification.

   #include <stdio.h>
   #include <ctype.h>
   #include <string.h>
   #define MAXWORD 100

   int getword(char *, int);
   struct key *binsearch(char *, struct key *, int);

   /* count C keywords; pointer version */
       char word[MAXWORD];
       struct key *p;

       while (getword(word, MAXWORD) != EOF)
           if (isalpha(word[0]))
               if ((p=binsearch(word, keytab, NKEYS)) != NULL)
       for (p = keytab; p < keytab + NKEYS; p++)
           if (p->count > 0)
               printf("%4d %s\n", p->count, p->word);
       return 0;

   /* binsearch: find word in tab[0]...tab[n-1] */
   struct key *binsearch(char *word, struck key *tab, int n)
       int cond;
       struct key *low = &tab[0];
       struct key *high = &tab[n];
       struct key *mid;

       while (low < high) {
           mid = low + (high-low) / 2;
           if ((cond = strcmp(word, mid->word)) < 0)
               high = mid;
           else if (cond > 0)
               low = mid + 1;
               return mid;
       return NULL;
There are several things worthy of note here. First, the declaration of binsearch must indicate that it returns a pointer to struct key instead of an integer; this is declared both in the function prototype and in binsearch. If binsearch finds the word, it returns a pointer to it; if it fails, it returns NULL.

Second, the elements of keytab are now accessed by pointers. This requires significant changes in binsearch.

The initializers for low and high are now pointers to the beginning and just past the end of the table.

The computation of the middle element can no longer be simply

   mid = (low+high) / 2    /* WRONG */
because the addition of pointers is illegal. Subtraction is legal, however, so high-low is the number of elements, and thus
   mid = low + (high-low) / 2
sets mid to the element halfway between low and high.

The most important change is to adjust the algorithm to make sure that it does not generate an illegal pointer or attempt to access an element outside the array. The problem is that &tab[-1] and &tab[n] are both outside the limits of the array tab. The former is strictly illegal, and it is illegal to dereference the latter. The language definition does guarantee, however, that pointer arithmetic that involves the first element beyond the end of an array (that is, &tab[n]) will work correctly.

In main we wrote

   for (p = keytab; p < keytab + NKEYS; p++)
If p is a pointer to a structure, arithmetic on p takes into account the size of the structure, so p++ increments p by the correct amount to get the next element of the array of structures, and the test stops the loop at the right time.

Don't assume, however, that the size of a structure is the sum of the sizes of its members. Because of alignment requirements for different objects, there may be unnamed ``holes'' in a structure. Thus, for instance, if a char is one byte and an int four bytes, the structure

   struct {
       char c;
       int i;
might well require eight bytes, not five. The sizeof operator returns the proper value.

Finally, an aside on program format: when a function returns a complicated type like a structure pointer, as in

   struct key *binsearch(char *word, struct key *tab, int n)
the function name can be hard to see, and to find with a text editor. Accordingly an alternate style is sometimes used:
   struct key *
   binsearch(char *word, struct key *tab, int n)
This is a matter of personal taste; pick the form you like and hold to it.

C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

void main(){
struct tag{
int a;
char *name;

struct tag t1;
printf("enter num and name\n");
scanf("%d %s",&t1.a,t1.name);
printf("%d %s",t1.a,t1.name);

whats wrong with the above program?

View Tutorial          By: niru at 2012-07-21 07:26:27
2. View Comment

error is main fuuction declaration
void main()
output is:
1 prakash.
structure sizeof()=4,total size.

View Tutorial          By: T.M.Prakash.MCA. at 2012-09-20 12:26:52

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Charles
arraycopy example in Java
Action listeners in JSF
Automatically Including Preludes and Codas in JSP
Using realloc() Function in C
Handling multiple buttons in HTML Form in Struts
Fopen and Getc implementation program in C
Pointers to Structures example program in C
Pointers vs. Multi-dimensional Arrays in C
getch and ungetch in C
Bitwise Operators in C
Variables and Arithmetic Expressions in C
Differences between JavaServer Faces technology and Struts
assert() example program in C++
'double buffering' Sample program in J2ME
Converting Default Function Arguments in C++ to Java

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
Open, Creat, Close, Unlink system calls sample program in C
UNIX read and write system calls sample program in C
Using memset(), memcpy(), and memmove() in C
Character Counting sample program in C
register Variables in C
Listing Files and Directories sample program in C
Sum of the elements of an array in C
The Birth and history of C Programming Language
Functions in C
Data Types and Sizes in C
Variable Scope and functions in C
Pointers and Function Arguments in C
Pointers to Functions example in C
Basics of Structures in C
Pointers to Structures example program in C
Most Emailed Articles (in C)
Arguments - Call by Value in C
Increment and Decrement Operators in C
The if else statement in C
Do while Loops in C
Printing a simple histogram in C
The Birth and history of C Programming Language
Basics of C
Getting Started with C
Variables and Arithmetic Expressions in C
The for statement in C
Symbolic Constants using #define in C
File Copying in C
Character Counting sample program in C
Line Counting sample program in C
Word Counting sample program in C