Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define GROW_FACTOR 2
- #define INIT_SIZE 8
- #define NEW(kind, size) (kind*)reallocate(0, sizeof(kind) * size, NULL)
- #define GROW(kind, ptr, o, n) (kind*)reallocate(sizeof(kind) * o, sizeof(kind) * n, ptr)
- void* reallocate(int oldsize, int newsize, void* ptr) {
- /* Allocates/reallocates/deallocates a block
- of memory using malloc, realloc and free */
- if (oldsize == 0 && ptr == NULL) {
- return malloc(newsize);
- }
- else if (oldsize == 0 && ptr != NULL) {
- free(ptr);
- return NULL;
- }
- return realloc(ptr, newsize);
- }
- char* reverse(char* str) {
- /* Reverses a string. Returns a copy of the
- string on success and a null pointer on
- failure*/
- int len = strlen(str);
- char* result = NEW(char, len);
- if (result == NULL) {
- return NULL;
- }
- memset(result, 0, len);
- for (int i = len - 1; i >= 0; i--) {
- result[len - i - 1] = str[i];
- }
- result[len] = '\0';
- return result;
- }
- char* input(char* prompt) {
- /* Reads from stdin until a newline is pressed.
- Returns null upon allocation failure, or a pointer
- to char otherwise.
- Prompt is an optional message to show to the user
- */
- char* buffer = NEW(char, INIT_SIZE);
- if (buffer == NULL) {
- return NULL;
- }
- memset(buffer, 0, INIT_SIZE * sizeof(char));
- char current;
- int len = 0;
- int buflen = INIT_SIZE * sizeof(char);
- printf("%s", prompt);
- while ((current = getchar()) != '\n') {
- if (len == buflen) {
- buflen = sizeof(char) * len * GROW_FACTOR;
- buffer = GROW(char, buffer, len, buflen);
- if (buffer == NULL) {
- return NULL;
- }
- }
- buffer[len] = current;
- len++;
- }
- // Ogni tanto non mette il demone finale della stringa
- // if (len >= buflen) {
- // buffer[len] = '\0';
- // }
- buffer[len] = '\0';
- return buffer;
- }
- int main(int argc, char* argv[]) {
- /* I have no clue what I'm doing */
- char * buffer = input("> ");
- char* reversed = reverse(buffer);
- if (buffer == NULL) {
- printf("Error reading input");
- return -1;
- }
- if (reversed == NULL) {
- printf("Error reversing input");
- return -1;
- }
- printf("The reverse of '%s' is '%s'\n", buffer, reversed);
- printf("Length of strings is %lu bytes\n", strlen(buffer));
- free(buffer);
- free(reversed);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement