Short program

The instruction as follows: Given cat.h

1
2
#include<cstddef>
void cat(int* a, int* b, int* c, void (*dog)(int*, int*, int*)=NULL);


Write a program that creates three integers and passes them to the cat function, and print out the integers both before and after calling the function.
then write a function called dog, the dog function should produce the behavior of cat.
This is what I have, but it is not working.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include "cat.h"

using namespace std;

void dog(int* a, int* b, int* c)
{
  *a=1;
  *b=2;
  *c=3;
  cout << *a << endl;
  cout << *b << endl;
  cout << *c << endl;
}

int main()
{
  cat(int* a, int* b, int* c, dog);
  cout << *a << endl;
  cout << *b << endl;
  cout << *c << endl;
}
From what you have given me:

First:
cat does not have a body so you will get a linker error from that.

Second:
in your main a, b and c don't live any where you need to initialize(make them a var) first. when passing the pointer to a, b and c you use the &to get the address of it.

Like this, i hope its not your homework! hehe.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

using namespace std;

void cat(int* a, int* b, int* c, void(*dog)(int*, int*, int*) = NULL)
{
	dog(a, b, c);
}

void dog(int* a, int* b, int* c)
{
	*a = 1;
	*b = 2;
	*c = 3;
	cout << *a << endl;
	cout << *b << endl;
	cout << *c << endl;
}

int main()
{
	int a = 10;
	int b = 20;
	int c = 30;

	cout << a << endl;
	cout << b << endl;
	cout << c << endl;

	cat(&a, &b, &c, dog);

	cin.get();//wait so we dont exit.
}


What is happening:
main calls Cat which takes 3 int pointers(address of var) and a function pointer to dog.

cat then calls dog.

dog then changes the values a, b and c.

then you c out it all.
Topic archived. No new replies allowed.