In: Computer Science
Programming in C:-
1. Suppose that a variable 's' is an array of strings (i.e. a pointer array where each element points to a string).
Write an expression that obtains the length of the third string of 's'. You may assume that string.h has been included.
2.
Consider the following function whose purpose is to return an array of 3 strings that are initialized to the strings in the character arrays s1, s2, and s3:
#include <string.h> #include <stdlib.h> char** stringstoarray(char* s1, char* s2, char* s3) { // dynamically allocate space for the pointer array itself. char** strings = _________ strings[ 0 ] = strdup(s1); // initialize first string strings[ 1 ] = strdup(s2); // initialize first string strings[ 2 ] = strdup(s3); // initialize third string return strings; }
In order for the function for the function to carry out its purpose, fill in the blank with the necessary code.
3.
Suppose that a variable 's' is an array of strings (i.e. a pointer array where each element points to a string).
Write an expression that accesses the 4th character of the 8th string of 's'.
4.
Write the declaration of an array of 128 strings. Use 's' for the name of the variable.
Programming in C:-
1.
{
int totalstrings;
// totalstrings is no of
strings in array of string s;
char **s =
malloc(totalstrings * sizeof(char *));
int i;
// Alloctaing space for
each string in array;
for (i = 0; i <
totalstrings; ++i)
{
s[i]=(char *)malloc(stringsize+1); //stringsize is size of one
string;
}
// In order to return
lenth of third string of s (array of string)
return
(s[2].length());
}
2.
#include <string.h>
#include <stdlib.h>
char** stringstoarray(char* s1, char* s2,
char* s3)
{
// dynamically allocate space for the pointer
array itself.
char** strings=malloc(3 * sizeof(char
*));
int i;
//totalstrings is number of total string
totalstrings=3;
for (i = 0; i < totalstrings; ++i)
{
strings[i] = (char
*)malloc(stringsize+1); //stringsize is size of single string to be
put in array
}
strings[ 0 ] = strdup(s1); // initialize first
string
strings[ 1 ] = strdup(s2); // initialize first
string
strings[ 2 ] = strdup(s3); // initialize third
string
return strings;
}
3.
// In order to access 4th character of 8th
string in array 's'
return s[7][3];
4.
char **s= malloc(128 * sizeof(char *));
int i;
for(i=0;i<128;i++)
{
//stringsize is size of one string
s[i]=(char *)malloc(stringsize+1);
}