- #1
doktorwho
- 181
- 6
Homework Statement
I have to create a program that dynamically allocates a string and uses up no extra space (The string takes up as much space as it needs to),checks if entered string is 'please stop this', if it is then the prgogram exits and if it isn't then it continues, it makes a copy of that string and then searches through it to find every reaccurence of charachter 'a' and change it to 'i go first in the alphabet' then print out both the original string and the changed one.
The Attempt at a Solution
Here is my thinking:
I will create a pointer to a string and for each inputted charachter i will reallocate so that it uses just as much as i need it to.
C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *string, c, t;
int i = 0, k = 1;
string = (char*)malloc(sizeof(char));
printf("Enter your string: \n");
while (c != '\n') {
c = getc(stdin);
// I am reallocating for each charachter inputted
string = (char*)realloc(string, k * sizeof(char));
string[i] = c;
i++;
j++;
}
string[i] = '\0';
printf("\nYou entered : %s", string);
free(string);
}
C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *string, c, *t;
int i = 0, k = 1;
string = (char*)malloc(sizeof(char));
printf("Enter your string: \n");
while (c != '\n') {
c = getc(stdin);
// I am reallocating for each charachter inputted
string = (char*)realloc(string, k * sizeof(char));
string[i] = c;
i++;
k++;
}
string[i] = '\0';
// The part where i check if strings equals the invalid input. Dont know what's the case here..
if (strcmp(string,"please stop this") == 1) {
printf("You wanted to stop so here we go! \n");
return 0;
}
// The part where i copy the string into the new pointer t
t = (char*)malloc(strlen(string)*sizeof(char));
strcpy(t, string);
printf("\nThe entered string is : %s", t);
free(string);
free(t);
}