# 13409 - Make sentence >author: Utin ###### tags: `dynamic memory` --- ## Brief See the code below ## Solution 0 ```c= #include <stdio.h> #include <string.h> #include <stdlib.h> int len[101]; char* str[101]; int n, m; void add(int x, char* s); void del(int x, int k); void swap(int a, int b); void longest(); void all(); int main() { for (int i = 0; i < 101; i++) { str[i] = (char*) malloc(1); str[i][0] = '\0'; // 記得初始化 len[i] = 0; // 記得初始化 } scanf("%d %d", &n, &m); char op[8]; for (int i = 0; i < m; i++) { scanf("%s", op); if (op[1] == 'd') { int x; char s[101]; scanf("%d %s", &x, s); x -= 1; add(x, s); } else if (op[1] == 'e') { int x, k; scanf("%d %d", &x, &k); x -= 1; del(x, k); } else if (op[1] == 'w') { int a, b; scanf("%d %d", &a, &b); a -= 1; b -= 1; swap(a, b); } else if (op[1] == 'o') longest(); else if (op[1] == 'l') all(); } } void add(int x, char* s) { int temp_len = strlen(s); char* temp = (char*) malloc(temp_len + len[x] + 1); strcpy(temp, str[x]); strcpy(temp + len[x], s); free(str[x]); str[x] = temp; len[x] += temp_len; } void del(int x, int k) { if (k >= len[x]) { free(str[x]); str[x] = (char*) malloc(1); str[x][0] = '\0'; // 記得初始化 len[x] = 0; } else { len[x] -= k; char* temp = (char*) malloc(len[x] + 1); strncpy(temp, str[x], len[x]); temp[len[x]] = '\0'; //把結尾設'\0' free(str[x]); str[x] = temp; } } void swap(int a, int b) { char* temp = str[a]; str[a] = str[b]; str[b] = temp; int temp_len = len[a]; len[a] = len[b]; len[b] = temp_len; } void longest() { int max = len[0], index = 0; for (int i = 1; i < n; i++) { if (len[i] > max) { max = len[i]; index = i; } } printf("%d %s\n", len[index], str[index]); } void all() { for (int i = 0; i < n; i++) { printf("%s\n",str[i]); } } // By Utin ``` ## Reference