Pointers to Structures example program in C

By: Charles Emailed: 1609 times Printed: 2075 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 */
   main()
   {
       char word[MAXWORD];
       struct key *p;

       while (getword(word, MAXWORD) != EOF)
           if (isalpha(word[0]))
               if ((p=binsearch(word, keytab, NKEYS)) != NULL)
                   p->count++;
       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;
           else
               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

Comments(2)


1. View Comment

#include<stdio.h>
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:
a=1,
name=prakash,
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 )
Using memset(), memcpy(), and memmove() in C
Listing Files and Directories sample program in C
perror() Function - example program in C
Open, Creat, Close, Unlink system calls sample program in C
UNIX read and write system calls sample program in C
Using free() Function in C
assert() Function Example program in C
scanf and sscanf sample program in C
Sum of the elements of an array in C
Printing a simple histogram in C
lseek() sample program in C
Find square and square root for a given number in C
fgets(), fputs() - Line Input and Output - sample program in C
Fopen and Getc implementation program in C
Sorting an integer array in C
Most Emailed Articles (in C)
Address Arithmetic and pointers in C
Macro Substitution using #define in C
Pointers to Structures example program in C
Getting Started with C
Variables and Arithmetic Expressions in C
register Variables in C
Trigonometric, Hyperbolic, Exponential and Logarithmic Functions in C
Printing a simple histogram in C
Symbolic Constants using #define in C
Arguments - Call by Value in C
Conditional Expressions in C
Functions returning non-integer values in C
Recursion in C
Tutorial on Complicated Declarations in C
Standard Input and Output in C