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

What parameters are needed to create a function for this code in C. Assume the f

ID: 3680906 • Letter: W

Question

What parameters are needed to create a function for this code in C. Assume the function will be called createArray(). How would it be implemented?

char **strArray = (char **)malloc(numStrings * sizeof(char *)); //Allocates an array of strings, for the number of strings defined during run time

   //numOfChars is an integer array that holds the number of characters of each string in the array
   // this loop allocates each member of the array to the appropriate length to hold the string
   // + 1 to hold the null terminator. pNumChars is a pointer to the integer array numOfChars
  
   for (i = 0; i < numStrings; i++)
   {

strArray[i] = (char *)malloc(*numOfChars + 1); //Allocate memory for the number of characters in each string of the string array
       pNumChars++; //point to next element in the array holding the character lengths of the strings
   }

Also, is this the correct way to allocate memory using "char **strArray = (char **)malloc(numStrings * sizeof(char *)"?

Explanation / Answer

A)

sizeof tells you the size of char*. You want strlen instead

if (argc < 2) {

    printf("Error - insufficient arguments ");

    return 1;

}

length=strlen(argv[1]);

buffer = (char*)malloc(length+1); // cast required for C++ only

Alternatively, if you're running on a Posix-compatible system, you could simplify things and use strdup instead:

buffer = strdup(argv[1])

Finally, make sure to free this memory when you're finished with it

free(buffer);

(b) The way we can declare:

You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:

char **strArray;

strArray = malloc(numstrings * sizeof(char*));

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