MakeShip() has the following function prototype: strict battleship makeShip (int
ID: 3811282 • Letter: M
Question
MakeShip() has the following function prototype: strict battleship makeShip (int. size, int pos); Input parameters: makeShip() takes as input the size and position of the ship. Return type: makeShip() returns a battleship structure. Functionality: makeShip() defines and initializes a battleship structure. It sets the battleship's member variables size and post based on its input parameters; it allocates a contiguous block of memory that is large enough to hold size integers and sets the member variable body to point to the start of the block: it assigns 1 to every element of body, which can be treated as an array with size elements after it has been allocated memory; and, finally, it returns the initialized battleship structure variable. Testing: Use the main source file test_1.c to test the functionality of makeShip(). Study this source file carefully since it will teach you how to (i) work with the battleship structure and (ii) write your own simple code to test functions.Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
struct battleship //structure definition
{
int size;
int pos;
};
struct battleship makeShip(int size,int pos) //function to dynamically allocate memory using pointer to structure ptr
{
struct battleship *ptr =(struct battleship *) malloc(sizeof(struct battleship));
ptr->size = size;
ptr->pos = pos;
return *ptr; // return value at ptr
}
int main()
{
int s,p;
printf(" Enter the size and position of battleship");
scanf("%d %d",&s,&p);
struct battleship bs = makeShip(s,p); //function call to allocate memory to structure variable bs
printf(" The size and position of battleship is %d and %d ",bs.size,bs.pos);
return 0;
}
output:
Enter the size and position of battleship 4 1
The size and position of battleship is 4 and 1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.