Professional Documents
Culture Documents
Week 10
Week 10
1) Pointers
2) Declare pointer variable
3) Searching algorithm
4) String, Array of strings
Pointers
Pointers are addresses
• A pointer is really the address of something in memory.
• Pointers are needed if it is required that a function change
the value of an object(through global variables could be
used).
• For example, the scanf function takes pointers as
arguments.
Pointers are not Integers
• It is possible to treat pointers as though they are integers
since they hold actual addresses in memory i-e 7232.
• printf, scanf, assignment and some of the arithmetic
operators work with pointers.
The * and & operators
&
It gives the address of something in memory, that is it
generates a pointer to the object.
*
• It gives what is pointed at by a pointer(called
dereferencing).
for example
int i=17;
Then the expression &i generates a pointer to the variable i.
• We can then find out what this pointer is pointing at by
applying the * operator to newly generated pointer.
Thus
*&i should have value 17.
Declare pointer variable
• To declare a pointer to an integer
int *ptr;
• Which says that type of *ptr is int, that is the object that
we find when following pointer ptr is an integer.
• Type of ptr is pointer to int, or int *.
• Declaring several pointers in a comma separated list
int *ptr1,ptr2,ptr3;
one pointer variable and two integer variable.
Declare pointer variable
main()
{
int i=17;
int *pi=&i;
*pi=25;
printf(“%d”,*pi);
printf(“%d”,pi);
return 0
}
Searching algorithm
Linear Search
Binary Search
#include<stdio.h>
#include<conio.h>
void main(void)
{
char name[81];
scanf(“%s”,name);
printf(“Greetings %s”,name);
}
#define MAX 5
#define LEN 40
void main(void)
{
int dex;
int enter=0;
char name[40];
char list[MAX][LEN]={“katrina”, “nigel”, “alistair”, “francesia”,
“gustan”};
printf(“enter your name”);
gets(name);
for(dex=0;dex<MAX;dex++)
if(strcmp(&list[dex][0],name)==0)
enter=1;
if(enter==1)
printf(“you may enter, oh honored one”);
else
printf(“guards!”remove the person”);