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*));
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.