In this lab, your tasks involve implementing programs that create and manipulate
ID: 673184 • Letter: I
Question
In this lab, your tasks involve implementing programs that create and manipulate strings. You will be using malloc, located in stdlib.h, to create space where you store strings, or pointers to strings, which you have created.
The functions strcpy, strcat, and strlen, both located in string.h, will be extremely helpful for this lab
Move into the easy directory and create the file reverse.c where you will write your program.
Your program will read in a single token from standard input. You will then display the reverse of this string as shown in the examples below.
You should use malloc to allocate a new string which will hold the reverse value. Make sure to include the NULL character in your calculations for how much memory you will need. Also, make sure to call free on any allocated memory you have created.
Here is how your program should be compiled and executed
Here is another run of your program
Explanation / Answer
#include <stdio.h>
int main(void) {
char str[255];
char *rev;
char ch;
int i=0, j, k;
printf("Enter a single word: ");
while(1) {
scanf("%c", &ch);
if(ch == ' ') {
str[i] = '';
break;
}
str[i] = ch;
i++;
}
rev = (char *)malloc(sizeof(char)*i);
rev[i] = '';
k=0;
for(j=i-1; j>=0; j--) {
rev[k] = str[j];
k++;
}
printf(" The reverse of "%s" is "%s"", str, rev);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.