Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Problem 2 Write a C function named copyStrArray that, given an integer \"count\"

ID: 3909904 • Letter: P

Question

Problem 2 Write a C function named copyStrArray that, given an integer "count" and an array "strArray" that contains "count" strings, returns a pointer to a complete ("deep") copy of the array. (In Java terminology, this would be a "clone".) For example, the program segment int main (int argc, char **argv) ( char **ptr ptrcopyStrArray (argc, argv) would place in ptr a pointer to a copy of argv, the command-line argument structure. You may assume that there is sufficient free memory in which to build the copied structure. Make no assumptions about the size of a pointer or a char (ie 64-bits vs 32-bits machine). Include all necessary casts, and allocate only as much memory as necessary. You may use any function in the stdio, stdlib, or string libraries.

Explanation / Answer

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

// function declaration
char** copyStrArray(int argc, char **argv);

int main(int argc, char **argv)
{
   char **ptr;
   ptr = copyStrArray(argc, argv);
   // uncomment the below lines to view the strings passed
//   int i;
//   for(i = 0; i < argc - 1; i++)
//   {
//       printf("%s ", ptr[i]);
//   }
  
   free (ptr);
}

char** copyStrArray(int argc, char **argv)
{
   int i;
   char **str;
   // allocating the number of strings as memory
   str = malloc(argc - 1);
   // looping from 0 to argc - 1
   for(i = 0; i < argc - 1; i++)
   {
       // allocating memory as length of each string
       // +1 as null character
       str[i] = malloc(strlen(argv[i + 1]) + 1);
       // copying the string
       strcpy(str[i], argv[i+1]);
   }
   return str;
}

C Program

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

// function declaration
char** copyStrArray(int argc, char **argv);

int main(int argc, char **argv)
{
   char **ptr;
   ptr = copyStrArray(argc, argv);
   // uncomment the below lines to view the strings passed
//   int i;
//   for(i = 0; i < argc - 1; i++)
//   {
//       printf("%s ", ptr[i]);
//   }
  
   free (ptr);
}

char** copyStrArray(int argc, char **argv)
{
   int i;
   char **str;
   // allocating the number of strings as memory
   str = malloc(argc - 1);
   // looping from 0 to argc - 1
   for(i = 0; i < argc - 1; i++)
   {
       // allocating memory as length of each string
       // +1 as null character
       str[i] = malloc(strlen(argv[i + 1]) + 1);
       // copying the string
       strcpy(str[i], argv[i+1]);
   }
   return str;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote