In: Computer Science
Problem 5
This problem is designed to make sure you can write a program that swaps data passed into it such that the caller's data has been swapped. This is something that is done very frequently in manipulating Data Structures.
The Solution / Test Requirements
I want your program to demonstrate that you understand how to swap information passed into a function and have the calling routine print out the data before and after the call to verify the data has been swapped. Call your functions Swap and SwapStructs. Swap is a function that receives the information to swap. The information is two integers. How should Swap receive them? How should it process them? SwapStructs is a function that receives two structs to swap. How should SwapStructs receive them? How should it process them?
Your Test Main must:
1. Declare two integers and initialize them to the values 1 and -1.
2. Print out the integers.
3. Call Swap to swap the values.
4. Print out the values on return from the function.
5. Declare a struct that holds 2 integers using a typedef for the struct.
6. Dynamically allocate two separate variables using the typedef and fill the dynamically allocated structs, filling the first with the values 10 and 20 and the second with 30 and 40.
7. Print out the values in each of the structs
8. Call SwapStructs to swap the contents of the structs.
9. Print out the values in the structs on return.
10. Free the memory that was dynamically allocated.
For your convenience, here is an output of my program:
Before call..I= 1, J=-1 After call.. I=-1, J= 1
Before SwapStructs..ptr1 contains 10 and 20
Before SwapStructs..ptr2 contains 30 and 40
After SwapStructs..ptr1 contains 30 and 40
After SwapStructs..ptr2 contains 10 and 20
Process returned 0 (0x0) execution time : 0.034 s Press any key to continue.
#include<stdio.h>
#include<iostream>
#include<malloc.h>
using namespace std;
void swap(int*,int*);
struct twoVar
{
int a;
int b;
};
typedef struct twoVar TwoVar;
void swapStructs(TwoVar*,TwoVar*);
int main()
{
int x=1,y=-1;
TwoVar *x1,*x2;
printf("\nbefore swapping x=%d and y=%d",x,y);
swap(&x,&y);
printf("\nafter swapping x=%d and y=%d",x,y);
x1=(TwoVar*)malloc(sizeof(TwoVar*));
x1->a=10;
x1->b=20;
x2=(TwoVar*)malloc(sizeof(TwoVar*));
x2->a=30;
x2->b=40;
printf("\nbefore swapping struct elements are x1->a=%d and x1->b=%d\nand x2->a=%d and x2->b=%d",x1->a,x1->b,x2->a,x2->b);
swapStructs(x1,x2);
printf("\nbefore swapping struct elements are x1->a=%d and x1->b=%d\nand x2->a=%d and x2->b=%d",x1->a,x1->b,x2->a,x2->b);
return 0;
}
void swapStructs(TwoVar* p,TwoVar* q)
{
TwoVar temp;
temp=*p;
*p=*q;
*q=temp;
}
void swap(int*p1,int*p2)
{
int temp=0;
temp=*p1;
*p1=*p2;
*p2=temp;
}