Question
C Language

Write the code that dynamically allocates an array of struct objects based on a size entered through the command line argumen
0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have included my code and screenshots in this answer. In case, there is any indentation issue due to editor, then please refer to code screenshots to avoid confusion.

--------------Code for main.c-------------------------

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <time.h>

typedef enum Color{RED, GREEN, BLUE} Color;

//struct MyStruct is declared
typedef struct MyStruct
{
   int value;
   Color color;
} MyStruct;

int main(int argc, char** argv)
{
   MyStruct *Arrayptr; //declare a pointer of type MyStruct, this pointer is used to access array
   int N;

   if(argc != 2)                       //if command line argument is not given exit
   {
       printf("\nGive additional command line argument\n");
       exit(1);
   }
   N = atoi(argv[1]);
   if(N <= 0) //if command line argument is not integer greater than 0, then exit
   {
       printf("\nGive additional command line argument as integer greater than 0\n");
       exit(1);
   }
   Arrayptr = (MyStruct*)malloc(N * sizeof(MyStruct)); //dynamically declare array of MyStruct of size N elements

   int i, r;
   Color enum_array[] = {RED, GREEN, BLUE};
   srand(time(0));
   for (i = 0; i < N; i++)                   //for each array element initialize
   {
       Arrayptr[i].value = i;         //initialize value to index of object
       r = rand()%3 + 1;                 //random number in range 0 to 3
       Arrayptr[i].color = enum_array[r]; //randomly select color and assign
   }


   printf("\nThe values for which color is RED: \n");
   for (i = 0; i < N; i++)
   {
       if(Arrayptr[i].color == RED) //for each array element if color value is RED then print its value
       {
           printf("%d ", Arrayptr[i].value);
       }
   }
   printf("\n\n");
   return 0;
}

--------------Screenshots for main.c-------------------------

-/c/enum_struct_cmdline_arg/main.c - Sublime Text (UNREGISTERED) 12:49 PM main.c { 18 { 20 { #include<stdio.h> 2 #include<std-/c/enum_struct_cmdline_arg/main.c - Sublime Text (UNREGISTERED) 12:49 PM main.c { 10 11 12 int value; Color color; } MyStruc

--------------Output for main.c-------------------------

) 12:49 PM vs@ubuntu: -/c/enum_struct_cmdline_arg vs@ubuntu:-/c/enum_struct_cmdline_args gcc main.c vs@ubuntu:-/c/enum_struct

---------------------------------------------------

I hope this helps you.

Please rate on this answer if it helped you,

Thank You for the opportunity.

Add a comment
Know the answer?
Add Answer to:
C Language Write the code that dynamically allocates an array of struct objects based on a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C Programming Language 2(a) Define a struct with 1 int array named i, 1 float array...

    C Programming Language 2(a) Define a struct with 1 int array named i, 1 float array named f, and one double array named d, each of size M. (b)Declare array x with N of those structs. (c)Write a void function to traverse array x (using a pointer) assigning to each element in each array d (in each struct in array x) the sum of the corresponding elements in arrays i and f (in the same struct). Use 3 pointers (of...

  • read it carefully C++ Question: Write a program that dynamically allocates an array large enough to...

    read it carefully C++ Question: Write a program that dynamically allocates an array large enough to hold a user-defined number of test scores. Once all the scores are entered, the array should be passed to a function that sorts them in ascending order. Another function should be called that calculates the average score. The program should display the sorted list of scores and averages with appropriate headings. Use pointer notation rather than array notation whenever possible. Input Validation: Do not...

  • Code in C language ADT: typedef struct{ int ID; float salary; int age; }Employee; ...

    code in C language ADT: typedef struct{ int ID; float salary; int age; }Employee; Specification: In this lab, five functions need to be implemented using the given ADT. 1. Employee* readRecord(FILE*) This function receives a FILE pointer created before. It reads a line from the provided csv file, and creates an Employee struct pointer with the information from that line then returns the pointer back to the calling function. Each line in the provided csv file contains the id, salary,...

  • Write the code to dynamically allocate ONE integer variable using calloc (contiguous allocation) or malloc (memory...

    Write the code to dynamically allocate ONE integer variable using calloc (contiguous allocation) or malloc (memory allocation) and have it pointed to by a pointer (of type int * ) named ptr_1. Use ptr_1 to assign the number 7 to that dynamically allocated integer, and in another line use printf to output the contents of that dynamically allocated integer variable. Write the code to dynamically allocate an integer array of length 5 using calloc or malloc and have it pointed...

  • In C. I want to read in the data of a text file into an array...

    In C. I want to read in the data of a text file into an array of dynamically allocated structs. The file is read as a command-line argument The text file format is: <number of classes in this file> <department name of class 1>:<number of class 1>:<location of class 1> <department name of class 2>:<number of class 2>:<location of class 2> ... Assume that no piece of information in the file contains a colon: the colons are only used as...

  • with c++ Write the code to make a complete copy of a hash table (using chaining) of the last chain (that exists) into a new linear linked list. Assume you know the size of the hash table (size M)....

    with c++ Write the code to make a complete copy of a hash table (using chaining) of the last chain (that exists) into a new linear linked list. Assume you know the size of the hash table (size M). The data in each node is a dynamically allocated array of characters. Write the code to make a complete copy of a hash table (using chaining) of the last chain (that exists) into a new linear linked list. Assume you know...

  • Write code in Java programming language. The ShoppingCart class will be composed with an array of...

    Write code in Java programming language. The ShoppingCart class will be composed with an array of Item objects. You do not need to implement the Item class for this question, only use it. Item has a getPrice() method that returns a float and a one-argument constructor that takes a float that specifies the price. The ShoppingCart class should have: Constructors: A no-argument and a single argument that takes an array of Items. Fields: • Items: an array of Item objects...

  • C programming The program will require the following structure: struct _data { char *name; long number;...

    C programming The program will require the following structure: struct _data { char *name; long number; }; The program will require command line arguments: int main(int argv, char **argc) { Where argv is the number of arguments and argc is an array holding the arguments (each is a string). Your program must catch any case where no command line arguement was provided and print a warning message (see below). You MUST include/use the following functions, defined as follows: int SCAN(FILE...

  • (C++) Write a function that accepts an int array and the array’s size as arguments. The function...

    (C++)Write a function that accepts an int array and the array’s size as arguments.The function should create a new array that is twice the size of the argument array.The function should copy the contents of the argument array to the new array, and initialize the unused elements of the second array with 0.The function should return a pointer to the new array.Demonstrate the function by using it in a main program that reads an integer N (that is not more...

  • Main topics: Files Program Specification: For this assignment, you need only write a single-file ...

    C program Main topics: Files Program Specification: For this assignment, you need only write a single-file C program. Your program will: Define the following C structure sample typedef struct int sarray size; the number of elements in this sanple's array floatsarray the sample's array of values sample Each sample holds a variable number of values, all taken together constitute a Sample Point Write a separate function to Read a file of delimited Sample Points into an array of pointers to...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT