Question

Malloc function

For the prelab assignment and the lab next week use malloc function to allocate space (to store the string) instead of creating fixed size character array. malloc function allows user to allocate memory (instead of compiler doing it by default) and this gives more control to the user and efficient allocation of the memory space.

Example

int *ptr

ptr=malloc(sizeof(int)*10);

In the example above integer pointer ptr is allocated a space of 10 blocks this is same as creating as array int ptr[10] but here malloc function is used which allows the user to decide how much memory is required.

Another example

char* string;

string = malloc(sizeof(char) * 15); //has room for 15 characters

Not even declaring the array is required, everything must be pointers.

Implement following functions for the pre-lab.

Description:

Implement following functions for the prelab assignment. These will be on the lab!

int main(): Declares a new string (char pointer), then calls getString and prints the string with the size out and frees the malloced memory from the string.

int getString(char *): This function takes in an uninitialized string, prompts the user for the size of the string (error checking to make sure size is between 1-20), and then prompts and scans in the actual string from the user and converts it to upper case. Returns the size of the string, and the string should be valid when the function terminates (hint: if the user enters in a string length less than the size but not empty, adjust the size. Using getSafeString from hw2 might be a good idea).

int checkString(char*, int): Takes in the string and the size, and checks to see if the string is valid. Valid string should contain only alphabetical characters ‘A’ through ‘Z’, not including the null terminator. Return 1 if string is valid, otherwise 0 if string is invalid. (hint: try using the acsii values instead of checking for specific characters)

Sample output:

Enter the size of the string: 109

Please enter again: -1

Please enter again: 7

Please enter the string: 0

Please enter a valid string: stringstringstring

The string entered is longer than the allowed size

Please enter a valid string: 89994

Please enter a valid string: 5tring5

Please enter a valid string: String

You entered: STRING which is size 6

./a.out

Enter the size of the string: 0

Please enter again: 18

Please enter the string: &#^I$@OI$

Please enter a valid string: baseball bat

Please enter a valid string: baseball

You entered: BASEBALL which is size 8

Note:

1. Don’t use any global variables, though a global constant for the maxsize of string (20) is ok.

2. Use only pointer notation and pointer arithmetic to implement the assignment.

3. Use the relevant library function, especially from ctype.h

Library function you’ll need to free the string at the end: https://www.tutorialspoint.com/c_standard_library/c_function_free.htm

Remember that the string is passed by reference to the function: changing its contents in the function changes it in main as well, including mallocing space for it.

Ascii table: http://www.asciitable.com/Malloc function- For the prelab assignment and the lab next week use malloc function to allocate space (to store the string) instead of creating fixed size character array. malloc function allows user to allocate memory (instead of compiler doing it by default) and this gives more control to the user and efficient allocation of the memory space. int *ptr ptr-malloc(sizeof(int)*10): In the example above integer pointer ptr is allocated a space of 10 blocks this is same as creating as array int pt[10] but here malloc function is used which allows the user to decide how much memory is required.» char string: string malloc(sizeef(char) 15); /has room for 15 characters eing the amay i reqpired eveything must be pointers.- Implement following functions for the pre-lab. 4

Please code in C and use sizeof to calculate the size of the string. Don't use strcpy.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The code is explained in screenshots comments :

int main() // Declaring char pointer char * stri int size- getstring (str)i free (str) / Freeing memory return 0;

67 68 69 70 71 72 73 74 75 76 if (j size) wed p printf(The string entered is longer than the allowed size\n) printf(Please

Output for the test cases :

Code :

#include <stdio.h>
#include <ctype.h>


int checkString(char *str,int size)
{
int i;
for(i=0;i<size;i++)
{
if(str[i]>='A'&&str[i]<='Z') // Check is char is between A-Z
{
continue;
}
else if(str[i]<='z'&&str[i]>='a') // Check char is between a-z
{
continue;
}
else
{
return 0; // If not return false.
}
}
return 1; // All char are ok return true.
}

int getString(char *str)
{
int size;

printf("Enter the size of the String: ");

while(1)
{
scanf("%d",&size);
if(size>0&&size<=20) // Checking size constraint.
{
break; // If size is correct then break.
}
printf("Please enter again: ");
}


printf("Please enter the string: ");
str = (char*)malloc(sizeof(char)); // Allocating string a char size of 1.
while(1)
{

char c = ' ';
int i = 0, j = 0;

str = (char*)malloc(sizeof(char));

fflush(stdin); // Flushing the input buffer present

while (c != '\n')
{
c = getc(stdin); // Taking char input
j++; // This is keeping track of the current size of string,
str = (char*)realloc(str, j * sizeof(char)); // Creating space for that char
str[i] = c; // Inserting char into created space
i++;
}
j--; // j will also increment on '\n' char so we will reduce j by 1

// Now j represents the current size of our string.

if(j>size) // If size of entered string is greter than allowed print error.
{
printf("The string entered is longer than the allowed size\n");
printf("Please enter a valid string: ");
continue;
}

if(checkString(str,j)==0) // Call check string funciton to check string contents.
{
printf("Please enter a valid string: ");
continue;
}

printf("You Entered: ");

for(i=0;i<j;i++)
{
if(str[i]<='z'&&str[i]>='a')
{
str[i] -= 32; // Converting string into uppercase as ascii differnce is 32
// Betweern Capital and small letters.
}
printf("%c",str[i]); // Printing string
}
printf(" which is size %d",j);

return j; // Returning size of string.
}

}

int main()
{
char *str; // Declaring char pointer

int size = getString(str);

free(str); // Freeing memory

return 0;

}

Add a comment
Know the answer?
Add Answer to:
Malloc function For the prelab assignment and the lab next week use malloc function to allocate...
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
  • Please use Visual Studio! Let me know if you need anything else <3 #include <stdio.h> #include...

    Please use Visual Studio! Let me know if you need anything else <3 #include <stdio.h> #include <string.h> #pragma warning(disable : 4996) // compiler directive for Visual Studio only // Read before you start: // You are given a partially complete program. Complete the functions in order for this program to work successfully. // All instructions are given above the required functions, please read them and follow them carefully. // You shoud not modify the function return types or parameters. //...

  • 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...

  • 1. You are given a C file which contains a partially completed program. Follow the instructions...

    1. You are given a C file which contains a partially completed program. Follow the instructions contained in comments and complete the required functions. You will be rewriting four functions from HW03 (initializeStrings, printStrings, encryptStrings, decryptStrings) using only pointer operations instead of using array operations. In addition to this, you will be writing two new functions (printReversedString, isValidPassword). You should not be using any array operations in any of functions for this assignment. You may use only the strlen() function...

  • IN C ONLY As mentioned earlier there are two changes we are going to make from...

    IN C ONLY As mentioned earlier there are two changes we are going to make from lab 5, The file you read into data structures can be any length. studentInfo array will be stored in another struct called studentList that will contain the Student pointer and current length of the list. Sometimes data can be used in structs that correlate between variables so it's convenient to store the data in the same struct. Instead of tracking a length variable all...

  • c++: Write a program to dynamically allocate memory for a C-style string on the heap for...

    c++: Write a program to dynamically allocate memory for a C-style string on the heap for up to 256 characters: Inside the main function: Allow the user to enter a word Pass the word to the function fun Write the function void fun(char *a) to: Print the word in Pig Latin. You can assume the word is all lowercase. The function should not alter the original array.

  • Hey everyone, I need help making a function with this directions with C++ Language. Can you...

    Hey everyone, I need help making a function with this directions with C++ Language. Can you guys use code like printf and fscanf without iostream or fstream because i havent study that yet. Thanks. Directions: Write a function declaration and definition for the char* function allocCat. This function should take in as a parameter a const Words pointer (Words is a defined struct) The function should allocate exactly enough memory for the concatenation of all of the strings in the...

  • Need help writing this lab. Directions in lab attachment above. Thank you. Output should look like...

    Need help writing this lab. Directions in lab attachment above. Thank you. Output should look like ones in attachment ab Ass Part 1 sing Static Arra Do this part on your own. Write a program named lab11 a.c containing the following function: preconditions arc is terminated by dest is big enough hold arc postconditions dest contains src and is terminated by "10" void my strcpy (char dest const char srclj) This function will take two character arrays as parameters. The...

  • Write in C Spring 2016 Lab Assignment 11 ET2100 In computer programming in general a "string"...

    Write in C Spring 2016 Lab Assignment 11 ET2100 In computer programming in general a "string" is a sequence of characters. In the C language anything within double quotes is a "string constant" so you have been seeing strings all semester. But we can also have string variables. In the C language these are implemented as an array of char, e.g. char name (10]: In order to make these variables easier to work with, it has been universally agreed that...

  • C++ Chapter 16 Problem: Implement #25 as a template function (Demonstrate using int, double, string, and...

    C++ Chapter 16 Problem: Implement #25 as a template function (Demonstrate using int, double, string, and x,y pair object) 24. Write a function that searches a numeric array for a specified value. The function should return the subscript of the element containing the value if it is found in the array. If the value is not found, the function should throw an exception. 25. Write a function that dynamically allocates a block of memory and returns a char pointer to...

  • Help please this is C/C++ code /* * Lab12, the purpose of this lab is to...

    Help please this is C/C++ code /* * Lab12, the purpose of this lab is to improve your skills in handling c strings * with pointers . * use of : strlen ,string concatenation strcat, compare strcmp, * copy strcpy and search strrchr * */ #include <cstdlib> #include <iostream> #include<cstring> using namespace std; /** * Create a method that prompts the user for only lowercase letters to represent * a name. * Start a Label, then prompt the user 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