100% found this document useful (1 vote)
21 views7 pages

Pointers and User Defined Types

The document provides an overview of pointers and user-defined types in C programming, detailing how pointers are declared, initialized, and used for memory manipulation, as well as their relationship with arrays. It also explains structures and unions, including their definitions, member access, and examples of usage in programs. Additional notes on field-width specifiers for formatted output in C are included.

Uploaded by

Bethwel Kipruto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
21 views7 pages

Pointers and User Defined Types

The document provides an overview of pointers and user-defined types in C programming, detailing how pointers are declared, initialized, and used for memory manipulation, as well as their relationship with arrays. It also explains structures and unions, including their definitions, member access, and examples of usage in programs. Additional notes on field-width specifiers for formatted output in C are included.

Uploaded by

Bethwel Kipruto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

POINTER

Pointer is a variable that doesn’t represent a value but holds that address of another variable i.e. a variable can
be declared as a pointer variable and point to the actual memory address of any data type variable in which a
value is stored. Pointers are usually used to provide much power and utility for C programmers to access and
manipulate data in ways not seen in some other languages. They are also useful for passing parameters into
functions in a manner that allows a function to modify and return values to the calling routine. However when
used incorrectly, they can be a frequent source of program bugs and programmer frustration.
Note: Just as data is modified when a normal variable is used, the value of the address stored in a pointer is
modified as the pointer variable is manipulated.

Declaring pointer variables


A pointer variable is declared in the same way as other variables but an asterisk symbol should precede the
variable name.

Examples
i) int * k, b;
k is a pointer variable which can hold the address of any integer type variable while b is a normal integer
variable.
ii) char * c;
c is a pointer variable pointing to a character type variable. In summary a pointer variable can be declared with
what they are pointing to.

Initialising pointer variables


A pointer variable can only be initialised with the address of a variable e.g. int i, *j = &i; in this given case, j is
a pointer variable initialised with the memory address of i.

Pointer Dereferencing
Dereferencing allows manipulation of the data contained at the memory address stored in the pointer. Usually
dereferencing allows the data at the memory address to be modified. The unary operator * is used to dereference.

Pointer Arithmetic
Part of power of pointers comes from the ability to perform arithmetic on the pointers themselves. They can be
incremented, decremented and manipulated using arithmetic expressions

Examples
The following programs illustrate the declaration and initialisation of pointer variables
i)
# include <stdio.h>
int main ()
{
int* a, b;
/*Initialization of a and b*/
b = 5;
a = &b;
/*Display the value of b using a */
printf ("The value of b is %d\n",*a);
return 0;
}
ii)
# include <stdio.h>

Programming Notes ~ Wainaina


Page 1 of 7
int main ()
{
int m, n, *p;
m = 2;
p = &m;
n = m*2;
/*Display the value of m using. P*/
printf ("The value of m is %d\n", *p);
p = &n;
/*Display the value of n using p*/
printf ("The value of n is %d\n", *p);
return 0;
}
iii)
# include <stdio.h>
int main ()
{
int f, * p;
f = 123;
p = & f;
printf ("%d\n", (*p) ++);
printf ("%d\n", *p++);
return 0;
}
iv)
# include <stdio.h>
int main ()
{
int f, * p;
f = 123;
p = &f;
printf ("%d\n", ++*p);
printf ("%d\n", *++p);
return 0;
}

Relationship between Pointers and Arrays


Consider the following statements
float * pt3,*pt4;
float values[100], results[100];
pt3=&values[0];
/*The address of the first element of “values” is stored in pt3*/
pt3++;
/*pt3 now contains the address of the second element of values*/
*pt3=45;
/*The second element of vales contains 45*/
pt3+=25;
/*pt3 now’s points at the 27th element of values*/
*pt3=1415. 2333;
/*The 27th element of values is now 1415.2333*/

Programming Notes ~ Wainaina


Page 2 of 7
pt3=values;
/*Now pt3 points at the start of values*/

/*The following program segment sets the entire array to 77.7*


for(i=0;i<100;i++)
{
*pt3++=77.7;
}

/*The contents of the address contained in pt3 are assigned to the contents
of the address contained in pt4*/
pt3=&values[0];
pt4=&results[0];
for(i=0;i<100;i++)
{
*pt4=*pt3;
pt4++;
pt3++;
}

Example
Write a program which incorporates a function using parameter passing and performs addition of the two
numbers. The function returns a value to the calling function. The parameters are passed by reference

#include<stdio.h>
/* ANSI function prototypes*/
int add(int *, int *);
/* add function definition*/
int add(int * num1, int * num2)
{
return *num1 + *num2;
}
/* main function definition*/
int main()
{
int number1, number2, sum;
printf("Enter two integer numbers\n");
scanf("%d%d",&number1, &number2);
sum= add (&number1,&number2);
printf("The sum of two numbers is %d\n",sum);
return 0;
}

Programming Notes ~ Wainaina


Page 3 of 7
USER DEFINED TYPES
1: STRUCTURES
A structure is a derived datatype suitable for grouping related data elements together under one name.
Structures may contain variables of many different datatypes in contrast to arrays that contain only elements of
the same datatypes.

Structure Definitions
The following is an example of structure definition
struct date {
int day;
int month;
int year;
};
The keyword struct introduces the structure definition. The identifier date is the structure tag and names the
structure definition. It is used with the keyword struct to declare variables of the structure type, in this case the
structure type is struct date. Variables declared within the braces of the structure definition are structure
members. Structure definition does not reserve any space in the memory; rather the definition creates a new data
type that is used to declare variables. Structure variables are declared like any variables of the basic datatype as
shown below:

struct date today;

This statement declares a variable called today of the date structure, struct date

Structure Members Operators


There are used access a structure member via the structure variable name and there are two types:

i) Dot Operator (.):


The dot operator access members of structure variables
Syntax: Variable_name.member;

ii) Pointer to structure operator (- >):


It is used to access members of dynamically created structure variables
Syntax: Variable_name -> member;

Notice that the operators are used as connectors.

Example I: Write a program that uses a structure called struct date with members day, month, year all of
integer data type. The structure variable should be initialised to the values of today’s date and display the same
on the screen.

#include<stdio.h>
int main()
{
struct date
{
int day;
int month;
int year;
};

Programming Notes ~ Wainaina


Page 4 of 7
/* Declare a variable of type struct date*/
struct date today;

/* Initialise the structure variable to the values of today’s


date*/
today.day=18;
today.month=10;
today.year=2000;
/* Display the values of the structure variable on the screen*/
printf("%d-%d-%d\n", today.day, today.month, today.year );
return 0;
}

Example II: Write a program that accepts today’s date and display it on the screen using a suitable format.
Define a structure with day, month and year as elements.

#include<stdio.h>
struct date
{
int day;
int month;
int year;
};
int main()
{

/* Declare a variable of type struct date*/


struct date today;
printf("Enter Day, Month and Year\n");
scanf("%d%d%d", &today.day, &today.month, &today.year);
/* Display the values of the structure variable on the screen*/
printf("%d-%d-%d\n", today.day, today.month, today.year);
return 0;
}

Example III: The following details are available for a student: Student Number, Name, Mark1, Mark2 and
Mark3. Write a program to include a structure called ‘students’ to store the details and display the same along
with average mark and “Pass”, if average mark is greater than or equal to 50 or “Fail” otherwise.
The program should record details of as many students as the user desires. The maximum number of students
should not exceed 50.

#include<stdio.h>
struct students
{

int stud_no;
char name[20];
float mark1, mark2, mark3;
};
int main()
{
struct students stud[50];
int i,no;
float average;
printf("Enter the number of the students\n");
scanf("%d",&no);

Programming Notes ~ Wainaina


Page 5 of 7
for(i=0;i<no;i++)
{
printf("Enter the student number\n");
scanf("%d",&stud[i].stud_no);
printf("Enter the student name\n");
scanf("%s",stud[i].name);
printf("Enter the student mark1, mark2,mark3\n");
scanf("%f%f%f",&stud[i].mark1,&stud[i].mark2,&stud[i].mark3);
}

printf("Stud No\tName\tMark1\tMark2\tMark3\tAverage\Grade\n");
for (i=0; i<no; i++)
{
average=(stud[i].mark1+stud[i].mark2+stud[i].mark3)/3;
printf("%d\t%s\t",stud[i].stud_no,stud[i].name);
printf("%0.2f\t%0.2f\t%0.2f\t",
stud[i].mark1,stud[i].mark2,stud[i].mark3);
printf("%0.2f\t",average);
if(average>=50)
printf("Pass\n");
else
printf("Fail\n");
}
return 0;
}

Exercises
1.
i) Define a structure called record, which holds an integer called number, a character of five elements
called word and a floating-point number called sum.
ii) Declare a structure called sample, defined from the structure defined above.

2. The following details are available for an employee: employee number, employee name and basic
pay.
Write a program to include a structure called ‘Employees’ to store employees details and display the
same along with DA, CCA and gross salary in a suitable format. The following information is given:
DA=51% of basic pay
CCA = 1000
Gross salary = basic pay + DA + CCA
The program should record details of as many employees as the user desires. The maximum number of
employees should not exceed 80.

2: UNIONS
Union is a derived data type like a structure but whose members share the same storage space. A union shares
the space instead of wasting storage on variables that are not being used. The members of a union can be any
type and the number of bytes used to store a union must be at least enough to hold the largest member.
In most cases, unions contain two or more data types and only one member and thus one data type can be
referenced at a time.
A union is declared with the keyword union in the same format as structures. The following is an example of
union declaration

Programming Notes ~ Wainaina


Page 6 of 7
union number
{
int x;
float y;
};

In a declaration, a union may be initialised only with a value of the same type as the first union member
e.g. union number value={10}; ,where value is the union variable.

ADDITIONAL NOTES ON FIELD – WIDTH SPECIFIERS


Field-width specifier
Field-width specifier, e.g. %3d is used to display signed decimal in width of three, default is the best-fit width.
Example
int num=12;
printf("%3d”, num);
output is B12 where B is blank
Padding field-width specifier, i.e. %03d to display signed decimal in width of three and pad any spaces in front
with 0's, the default padding is the space character.
Example
int num=12;
printf("%03d”,num);

Output is 012
For floating point numbers, decimal point specifier is used i.e. %10.4f to display 5 digits for integer portion,
followed by a dot, then 4 digits for the decimal point portion. Take note that the dot is also counted as part of
the entire width.
Example
float num=12;
printf("%10.4f”, num);

Output is BBB12.0000 where B is blank


There is also a left-justified specifier, i.e. %-3d to display unsigned decimal in width of three with left-justified.
By default, all output is right-justified.
Example
int num=12;
printf("%-3d”, num);

Output is 12

Sign specifier, i.e. %+d to display signed decimal with a positive sign for positive number and negative sign
otherwise

Programming Notes ~ Wainaina


Page 7 of 7

You might also like