C26: Examples on Pointer Usage
Determine the output of the following program.
#include <stdio.h>
#include <string.h>
struct sample {
char *name;
int *id;
float price;
};
static char product[] = "Greggs Coffee";
static float price1 = 3.20;
static int id = 773;
void printrecord( struct sample * );
void printrecord( struct sample *goods )
{
printf("Name = %s\n", goods->name );
printf("ID = %d\n", *goods->id);
printf("Price = %.2f\n", goods->price );
goods->name = &product[0];
goods->id = &id;
goods->price = price1;
}
main()
{
int code = 123, number;
char name[] = "Apple Pie";
struct sample item;
item.id = &code;
item.price = 1.65;
item.name = name;
number = *item.id;
printrecord( &item );
printf("Name = %s\n", item.name );
printf("ID = %d\n", *item.id);
printf("Price = %.2f\n", item.price );
}
What are we trying to print out?
What does it evaluate to?
eg,
printf("ID = %d\n", *goods->id);
%d is an integer
we want the value to be a variable integer type
goods->id,
what is id, its a pointer, so we mean contents of,
therefor we use *goods->id
which evaluates to an integer type
Name = Apple Pie ID = 123 Price = 1.65 Name = Greggs Coffee ID = 773 Price = 3.20
©Copyright B Brown. 1984-1999. All rights reserved.