Duplicate a String

Lab C Intermediate 20 points

Write char *duplicate(char *s) that mallocs strlen(s) + 1 bytes and copies the string. Read words, duplicate each, reverse the copy, and print original and copy.

Input

n, then n words.

Output

n lines: original copy

Example

Input

2
hello
abc

Output

hello olleh
abc cba
Sample input available Sample output available
Editor
C

Hints

+1 makes room for the '\0'.

Solution explanation

Returning malloc'd memory is safe (unlike returning a local array); the caller must free it.

Show solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *duplicate(char *s) {
    char *copy = malloc(strlen(s) + 1);
    strcpy(copy, s);
    return copy;
}

int main() {
    int n;
    char w[100];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%s", w);
        char *c = duplicate(w);
        int len = strlen(c);
        for (int j = 0; j < len / 2; j++) {
            char t = c[j];
            c[j] = c[len - 1 - j];
            c[len - 1 - j] = t;
        }
        printf("%s %s\n", w, c);
        free(c);
    }
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD