C Programming

C26: Examples on Pointer Usage
This program introduces a structure which has pointers as some of its fields. The structure is passed to a function printrecord() as a reference and accessed via a pointer goods. This function also updates some of the fields.

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 );
}

Answer


©Copyright B Brown. 1984-1999. All rights reserved.