Programming with Data Structures
Programming with Data Structures
#include <stdio.h>
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
Pointers
Declaration of a pointer
data_type *identifier;
Example: int *x;
#include <stdio.h>
/* function to generate and return numbers */
int * getArray( ) {
static int r[10];
int i;
/* populate the array */
for ( i = 0; i < 10; ++i) {
printf(“Enter an integer”);
scanf(“%d”, &r[i]); }
return r;
Return array from function in C
/* main function to call above defined function */
int main () {
/* a pointer to an int */
int *p;
int i;
p = getArray();
struct identifier {
Data_type identifier1;
Data_type identifier2;
………
Data_type identifiern;
}identifiers;
Variables declared within the structure are referred as structure fields.
Identifiers are specified at the end to declare structure variables
Structures
// Structure example
struct students {
char Name[30], degree[3], regNo[10];
int age;
double tution_fee;
}std;
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use
the → operator as follows −
struct_pointer->title;
Pointers to Structures
Let us re-write the above example using structure pointer.
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
Pointers to Structures
Let us re-write the above example using structure pointer.
#include <stdio.h>
#include <string.h>
struct Books {
char title[50], author[50], subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book ) {
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
Pointers to Structures
/* function declaration */
void printBook( struct Books *book );
int main( ) {
struct Books Book1; /* Declare variables of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* print Book1 info by passing address of Book1 */
printBook( &Book1 ); // pass by reference
return 0; }